1 #![unstable(feature = "process_internals", issue = "0")]
3 use crate::collections::BTreeMap;
4 use crate::env::split_paths;
6 use crate::ffi::{OsString, OsStr};
9 use crate::io::{self, Error, ErrorKind};
11 use crate::os::windows::ffi::OsStrExt;
12 use crate::path::Path;
14 use crate::sys::mutex::Mutex;
16 use crate::sys::fs::{OpenOptions, File};
17 use crate::sys::handle::Handle;
18 use crate::sys::pipe::{self, AnonPipe};
19 use crate::sys::stdio;
21 use crate::sys_common::{AsInner, FromInner, IntoInner};
22 use crate::sys_common::process::CommandEnv;
23 use crate::borrow::Borrow;
25 use libc::{c_void, EXIT_SUCCESS, EXIT_FAILURE};
27 ////////////////////////////////////////////////////////////////////////////////
29 ////////////////////////////////////////////////////////////////////////////////
31 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
33 pub struct EnvKey(OsString);
35 impl From<OsString> for EnvKey {
36 fn from(k: OsString) -> Self {
37 let mut buf = k.into_inner().into_inner();
38 buf.make_ascii_uppercase();
39 EnvKey(FromInner::from_inner(FromInner::from_inner(buf)))
43 impl From<EnvKey> for OsString {
44 fn from(k: EnvKey) -> Self { k.0 }
47 impl Borrow<OsStr> for EnvKey {
48 fn borrow(&self) -> &OsStr { &self.0 }
51 impl AsRef<OsStr> for EnvKey {
52 fn as_ref(&self) -> &OsStr { &self.0 }
56 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
57 if str.as_ref().encode_wide().any(|b| b == 0) {
58 Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"))
68 cwd: Option<OsString>,
70 detach: bool, // not currently exposed in std::process
72 stdout: Option<Stdio>,
73 stderr: Option<Stdio>,
83 pub struct StdioPipes {
84 pub stdin: Option<AnonPipe>,
85 pub stdout: Option<AnonPipe>,
86 pub stderr: Option<AnonPipe>,
89 struct DropGuard<'a> {
94 pub fn new(program: &OsStr) -> Command {
96 program: program.to_os_string(),
98 env: Default::default(),
108 pub fn arg(&mut self, arg: &OsStr) {
109 self.args.push(arg.to_os_string())
111 pub fn env_mut(&mut self) -> &mut CommandEnv {
114 pub fn cwd(&mut self, dir: &OsStr) {
115 self.cwd = Some(dir.to_os_string())
117 pub fn stdin(&mut self, stdin: Stdio) {
118 self.stdin = Some(stdin);
120 pub fn stdout(&mut self, stdout: Stdio) {
121 self.stdout = Some(stdout);
123 pub fn stderr(&mut self, stderr: Stdio) {
124 self.stderr = Some(stderr);
126 pub fn creation_flags(&mut self, flags: u32) {
130 pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
131 -> io::Result<(Process, StdioPipes)> {
132 let maybe_env = self.env.capture_if_changed();
133 // To have the spawning semantics of unix/windows stay the same, we need
134 // to read the *child's* PATH if one is provided. See #15149 for more
136 let program = maybe_env.as_ref().and_then(|env| {
137 if let Some(v) = env.get(OsStr::new("PATH")) {
138 // Split the value and test each path to see if the
140 for path in split_paths(&v) {
141 let path = path.join(self.program.to_str().unwrap())
142 .with_extension(env::consts::EXE_EXTENSION);
143 if fs::metadata(&path).is_ok() {
144 return Some(path.into_os_string())
151 let mut si = zeroed_startupinfo();
152 si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
153 si.dwFlags = c::STARTF_USESTDHANDLES;
155 let program = program.as_ref().unwrap_or(&self.program);
156 let mut cmd_str = make_command_line(program, &self.args)?;
157 cmd_str.push(0); // add null terminator
159 // stolen from the libuv code.
160 let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
162 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
165 let (envp, _data) = make_envp(maybe_env)?;
166 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
167 let mut pi = zeroed_process_information();
169 // Prepare all stdio handles to be inherited by the child. This
170 // currently involves duplicating any existing ones with the ability to
171 // be inherited by child processes. Note, however, that once an
172 // inheritable handle is created, *any* spawned child will inherit that
173 // handle. We only want our own child to inherit this handle, so we wrap
174 // the remaining portion of this spawn in a mutex.
176 // For more information, msdn also has an article about this race:
177 // http://support.microsoft.com/kb/315939
178 static CREATE_PROCESS_LOCK: Mutex = Mutex::new();
179 let _guard = DropGuard::new(&CREATE_PROCESS_LOCK);
181 let mut pipes = StdioPipes {
186 let null = Stdio::Null;
187 let default_stdin = if needs_stdin {&default} else {&null};
188 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
189 let stdout = self.stdout.as_ref().unwrap_or(&default);
190 let stderr = self.stderr.as_ref().unwrap_or(&default);
191 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
192 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE,
194 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
196 si.hStdInput = stdin.raw();
197 si.hStdOutput = stdout.raw();
198 si.hStdError = stderr.raw();
201 cvt(c::CreateProcessW(ptr::null(),
202 cmd_str.as_mut_ptr(),
205 c::TRUE, flags, envp, dirp,
209 // We close the thread handle because we don't care about keeping
210 // the thread id valid, and we aren't keeping the thread handle
211 // around to be able to close it later.
212 drop(Handle::new(pi.hThread));
214 Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
219 impl fmt::Debug for Command {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(f, "{:?}", self.program)?;
222 for arg in &self.args {
223 write!(f, " {:?}", arg)?;
229 impl<'a> DropGuard<'a> {
230 fn new(lock: &'a Mutex) -> DropGuard<'a> {
238 impl<'a> Drop for DropGuard<'a> {
247 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
248 -> io::Result<Handle> {
250 // If no stdio handle is available, then inherit means that it
251 // should still be unavailable so propagate the
252 // INVALID_HANDLE_VALUE.
254 match stdio::get_handle(stdio_id) {
256 let io = Handle::new(io);
257 let ret = io.duplicate(0, true,
258 c::DUPLICATE_SAME_ACCESS);
262 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
267 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
268 let pipes = pipe::anon_pipe(ours_readable, true)?;
269 *pipe = Some(pipes.ours);
270 Ok(pipes.theirs.into_handle())
273 Stdio::Handle(ref handle) => {
274 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
277 // Open up a reference to NUL with appropriate read/write
278 // permissions as well as the ability to be inherited to child
279 // processes (as this is about to be inherited).
281 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
282 let mut sa = c::SECURITY_ATTRIBUTES {
283 nLength: size as c::DWORD,
284 lpSecurityDescriptor: ptr::null_mut(),
287 let mut opts = OpenOptions::new();
288 opts.read(stdio_id == c::STD_INPUT_HANDLE);
289 opts.write(stdio_id != c::STD_INPUT_HANDLE);
290 opts.security_attributes(&mut sa);
291 File::open(Path::new("NUL"), &opts).map(|file| {
299 impl From<AnonPipe> for Stdio {
300 fn from(pipe: AnonPipe) -> Stdio {
301 Stdio::Handle(pipe.into_handle())
305 impl From<File> for Stdio {
306 fn from(file: File) -> Stdio {
307 Stdio::Handle(file.into_handle())
311 ////////////////////////////////////////////////////////////////////////////////
313 ////////////////////////////////////////////////////////////////////////////////
315 /// A value representing a child process.
317 /// The lifetime of this value is linked to the lifetime of the actual
318 /// process - the Process destructor calls self.finish() which waits
319 /// for the process to terminate.
325 pub fn kill(&mut self) -> io::Result<()> {
327 c::TerminateProcess(self.handle.raw(), 1)
332 pub fn id(&self) -> u32 {
334 c::GetProcessId(self.handle.raw()) as u32
338 pub fn wait(&mut self) -> io::Result<ExitStatus> {
340 let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
341 if res != c::WAIT_OBJECT_0 {
342 return Err(Error::last_os_error())
345 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
346 Ok(ExitStatus(status))
350 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
352 match c::WaitForSingleObject(self.handle.raw(), 0) {
353 c::WAIT_OBJECT_0 => {}
357 _ => return Err(io::Error::last_os_error()),
360 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
361 Ok(Some(ExitStatus(status)))
365 pub fn handle(&self) -> &Handle { &self.handle }
367 pub fn into_handle(self) -> Handle { self.handle }
370 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
371 pub struct ExitStatus(c::DWORD);
374 pub fn success(&self) -> bool {
377 pub fn code(&self) -> Option<i32> {
382 impl From<c::DWORD> for ExitStatus {
383 fn from(u: c::DWORD) -> ExitStatus {
388 impl fmt::Display for ExitStatus {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 // Windows exit codes with the high bit set typically mean some form of
391 // unhandled exception or warning. In this scenario printing the exit
392 // code in decimal doesn't always make sense because it's a very large
393 // and somewhat gibberish number. The hex code is a bit more
394 // recognizable and easier to search for, so print that.
395 if self.0 & 0x80000000 != 0 {
396 write!(f, "exit code: {:#x}", self.0)
398 write!(f, "exit code: {}", self.0)
403 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
404 pub struct ExitCode(c::DWORD);
407 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
408 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
411 pub fn as_i32(&self) -> i32 {
416 fn zeroed_startupinfo() -> c::STARTUPINFO {
419 lpReserved: ptr::null_mut(),
420 lpDesktop: ptr::null_mut(),
421 lpTitle: ptr::null_mut(),
432 lpReserved2: ptr::null_mut(),
433 hStdInput: c::INVALID_HANDLE_VALUE,
434 hStdOutput: c::INVALID_HANDLE_VALUE,
435 hStdError: c::INVALID_HANDLE_VALUE,
439 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
440 c::PROCESS_INFORMATION {
441 hProcess: ptr::null_mut(),
442 hThread: ptr::null_mut(),
448 // Produces a wide string *without terminating null*; returns an error if
449 // `prog` or any of the `args` contain a nul.
450 fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> {
451 // Encode the command and arguments in a command line string such
452 // that the spawned process may recover them using CommandLineToArgvW.
453 let mut cmd: Vec<u16> = Vec::new();
454 // Always quote the program name so CreateProcess doesn't interpret args as
455 // part of the name if the binary wasn't found first time.
456 append_arg(&mut cmd, prog, true)?;
458 cmd.push(' ' as u16);
459 append_arg(&mut cmd, arg, false)?;
463 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr, force_quotes: bool) -> io::Result<()> {
464 // If an argument has 0 characters then we need to quote it to ensure
465 // that it actually gets passed through on the command line or otherwise
466 // it will be dropped entirely when parsed on the other end.
467 ensure_no_nuls(arg)?;
468 let arg_bytes = &arg.as_inner().inner.as_inner();
469 let quote = force_quotes || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
470 || arg_bytes.is_empty();
472 cmd.push('"' as u16);
475 let mut backslashes: usize = 0;
476 for x in arg.encode_wide() {
477 if x == '\\' as u16 {
481 // Add n+1 backslashes to total 2n+1 before internal '"'.
482 cmd.extend((0..=backslashes).map(|_| '\\' as u16));
490 // Add n backslashes to total 2n before ending '"'.
491 cmd.extend((0..backslashes).map(|_| '\\' as u16));
492 cmd.push('"' as u16);
498 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>)
499 -> io::Result<(*mut c_void, Vec<u16>)> {
500 // On Windows we pass an "environment block" which is not a char**, but
501 // rather a concatenation of null-terminated k=v\0 sequences, with a final
503 if let Some(env) = maybe_env {
504 let mut blk = Vec::new();
507 blk.extend(ensure_no_nuls(k.0)?.encode_wide());
508 blk.push('=' as u16);
509 blk.extend(ensure_no_nuls(v)?.encode_wide());
513 Ok((blk.as_mut_ptr() as *mut c_void, blk))
515 Ok((ptr::null_mut(), Vec::new()))
519 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
523 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
525 Ok((dir_str.as_ptr(), dir_str))
527 None => Ok((ptr::null(), Vec::new()))
533 use crate::ffi::{OsStr, OsString};
534 use super::make_command_line;
537 fn test_make_command_line() {
538 fn test_wrapper(prog: &str, args: &[&str]) -> String {
539 let command_line = &make_command_line(OsStr::new(prog),
541 .map(|a| OsString::from(a))
542 .collect::<Vec<OsString>>())
544 String::from_utf16(command_line).unwrap()
548 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
549 "\"prog\" aaa bbb ccc"
553 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
554 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
557 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
558 "\"C:\\Program Files\\test\" aa\\\"bb"
561 test_wrapper("echo", &["a b c"]),
565 test_wrapper("echo", &["\" \\\" \\", "\\"]),
566 "\"echo\" \"\\\" \\\\\\\" \\\\\" \\"
569 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
570 "\"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}\""