1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![unstable(feature = "process_internals", issue = "0")]
14 use collections::BTreeMap;
17 use ffi::{OsString, OsStr};
20 use io::{self, Error, ErrorKind};
23 use os::windows::ffi::OsStrExt;
26 use sys::mutex::Mutex;
28 use sys::fs::{OpenOptions, File};
29 use sys::handle::Handle;
30 use sys::pipe::{self, AnonPipe};
33 use sys_common::{AsInner, FromInner, IntoInner};
34 use sys_common::process::{CommandEnv, EnvKey};
35 use alloc::borrow::Borrow;
37 ////////////////////////////////////////////////////////////////////////////////
39 ////////////////////////////////////////////////////////////////////////////////
41 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
43 pub struct WindowsEnvKey(OsString);
45 impl From<OsString> for WindowsEnvKey {
46 fn from(k: OsString) -> Self {
47 let mut buf = k.into_inner().into_inner();
48 buf.make_ascii_uppercase();
49 WindowsEnvKey(FromInner::from_inner(FromInner::from_inner(buf)))
53 impl From<WindowsEnvKey> for OsString {
54 fn from(k: WindowsEnvKey) -> Self { k.0 }
57 impl Borrow<OsStr> for WindowsEnvKey {
58 fn borrow(&self) -> &OsStr { &self.0 }
61 impl AsRef<OsStr> for WindowsEnvKey {
62 fn as_ref(&self) -> &OsStr { &self.0 }
65 impl EnvKey for WindowsEnvKey {}
68 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
69 if str.as_ref().encode_wide().any(|b| b == 0) {
70 Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"))
79 env: CommandEnv<WindowsEnvKey>,
80 cwd: Option<OsString>,
82 detach: bool, // not currently exposed in std::process
84 stdout: Option<Stdio>,
85 stderr: Option<Stdio>,
95 pub struct StdioPipes {
96 pub stdin: Option<AnonPipe>,
97 pub stdout: Option<AnonPipe>,
98 pub stderr: Option<AnonPipe>,
101 struct DropGuard<'a> {
106 pub fn new(program: &OsStr) -> Command {
108 program: program.to_os_string(),
110 env: Default::default(),
120 pub fn arg(&mut self, arg: &OsStr) {
121 self.args.push(arg.to_os_string())
123 pub fn env_mut(&mut self) -> &mut CommandEnv<WindowsEnvKey> {
126 pub fn cwd(&mut self, dir: &OsStr) {
127 self.cwd = Some(dir.to_os_string())
129 pub fn stdin(&mut self, stdin: Stdio) {
130 self.stdin = Some(stdin);
132 pub fn stdout(&mut self, stdout: Stdio) {
133 self.stdout = Some(stdout);
135 pub fn stderr(&mut self, stderr: Stdio) {
136 self.stderr = Some(stderr);
138 pub fn creation_flags(&mut self, flags: u32) {
142 pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
143 -> io::Result<(Process, StdioPipes)> {
144 let maybe_env = self.env.capture_if_changed();
145 // To have the spawning semantics of unix/windows stay the same, we need
146 // to read the *child's* PATH if one is provided. See #15149 for more
148 let program = maybe_env.as_ref().and_then(|env| {
149 if let Some(v) = env.get(OsStr::new("PATH")) {
150 // Split the value and test each path to see if the
152 for path in split_paths(&v) {
153 let path = path.join(self.program.to_str().unwrap())
154 .with_extension(env::consts::EXE_EXTENSION);
155 if fs::metadata(&path).is_ok() {
156 return Some(path.into_os_string())
163 let mut si = zeroed_startupinfo();
164 si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
165 si.dwFlags = c::STARTF_USESTDHANDLES;
167 let program = program.as_ref().unwrap_or(&self.program);
168 let mut cmd_str = make_command_line(program, &self.args)?;
169 cmd_str.push(0); // add null terminator
171 // stolen from the libuv code.
172 let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
174 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
177 let (envp, _data) = make_envp(maybe_env)?;
178 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
179 let mut pi = zeroed_process_information();
181 // Prepare all stdio handles to be inherited by the child. This
182 // currently involves duplicating any existing ones with the ability to
183 // be inherited by child processes. Note, however, that once an
184 // inheritable handle is created, *any* spawned child will inherit that
185 // handle. We only want our own child to inherit this handle, so we wrap
186 // the remaining portion of this spawn in a mutex.
188 // For more information, msdn also has an article about this race:
189 // http://support.microsoft.com/kb/315939
190 static CREATE_PROCESS_LOCK: Mutex = Mutex::new();
191 let _guard = DropGuard::new(&CREATE_PROCESS_LOCK);
193 let mut pipes = StdioPipes {
198 let null = Stdio::Null;
199 let default_stdin = if needs_stdin {&default} else {&null};
200 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
201 let stdout = self.stdout.as_ref().unwrap_or(&default);
202 let stderr = self.stderr.as_ref().unwrap_or(&default);
203 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
204 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE,
206 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
208 si.hStdInput = stdin.raw();
209 si.hStdOutput = stdout.raw();
210 si.hStdError = stderr.raw();
213 cvt(c::CreateProcessW(ptr::null(),
214 cmd_str.as_mut_ptr(),
217 c::TRUE, flags, envp, dirp,
221 // We close the thread handle because we don't care about keeping
222 // the thread id valid, and we aren't keeping the thread handle
223 // around to be able to close it later.
224 drop(Handle::new(pi.hThread));
226 Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
231 impl fmt::Debug for Command {
232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233 write!(f, "{:?}", self.program)?;
234 for arg in &self.args {
235 write!(f, " {:?}", arg)?;
241 impl<'a> DropGuard<'a> {
242 fn new(lock: &'a Mutex) -> DropGuard<'a> {
245 DropGuard { lock: lock }
250 impl<'a> Drop for DropGuard<'a> {
259 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
260 -> io::Result<Handle> {
262 // If no stdio handle is available, then inherit means that it
263 // should still be unavailable so propagate the
264 // INVALID_HANDLE_VALUE.
266 match stdio::get(stdio_id) {
268 let io = Handle::new(io.handle());
269 let ret = io.duplicate(0, true,
270 c::DUPLICATE_SAME_ACCESS);
274 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
279 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
280 let pipes = pipe::anon_pipe(ours_readable)?;
281 *pipe = Some(pipes.ours);
283 c::SetHandleInformation(pipes.theirs.handle().raw(),
284 c::HANDLE_FLAG_INHERIT,
285 c::HANDLE_FLAG_INHERIT)
287 Ok(pipes.theirs.into_handle())
290 Stdio::Handle(ref handle) => {
291 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
294 // Open up a reference to NUL with appropriate read/write
295 // permissions as well as the ability to be inherited to child
296 // processes (as this is about to be inherited).
298 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
299 let mut sa = c::SECURITY_ATTRIBUTES {
300 nLength: size as c::DWORD,
301 lpSecurityDescriptor: ptr::null_mut(),
304 let mut opts = OpenOptions::new();
305 opts.read(stdio_id == c::STD_INPUT_HANDLE);
306 opts.write(stdio_id != c::STD_INPUT_HANDLE);
307 opts.security_attributes(&mut sa);
308 File::open(Path::new("NUL"), &opts).map(|file| {
316 impl From<AnonPipe> for Stdio {
317 fn from(pipe: AnonPipe) -> Stdio {
318 Stdio::Handle(pipe.into_handle())
322 impl From<File> for Stdio {
323 fn from(file: File) -> Stdio {
324 Stdio::Handle(file.into_handle())
328 ////////////////////////////////////////////////////////////////////////////////
330 ////////////////////////////////////////////////////////////////////////////////
332 /// A value representing a child process.
334 /// The lifetime of this value is linked to the lifetime of the actual
335 /// process - the Process destructor calls self.finish() which waits
336 /// for the process to terminate.
342 pub fn kill(&mut self) -> io::Result<()> {
344 c::TerminateProcess(self.handle.raw(), 1)
349 pub fn id(&self) -> u32 {
351 c::GetProcessId(self.handle.raw()) as u32
355 pub fn wait(&mut self) -> io::Result<ExitStatus> {
357 let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
358 if res != c::WAIT_OBJECT_0 {
359 return Err(Error::last_os_error())
362 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
363 Ok(ExitStatus(status))
367 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
369 match c::WaitForSingleObject(self.handle.raw(), 0) {
370 c::WAIT_OBJECT_0 => {}
374 _ => return Err(io::Error::last_os_error()),
377 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
378 Ok(Some(ExitStatus(status)))
382 pub fn handle(&self) -> &Handle { &self.handle }
384 pub fn into_handle(self) -> Handle { self.handle }
387 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
388 pub struct ExitStatus(c::DWORD);
391 pub fn success(&self) -> bool {
394 pub fn code(&self) -> Option<i32> {
399 impl From<c::DWORD> for ExitStatus {
400 fn from(u: c::DWORD) -> ExitStatus {
405 impl fmt::Display for ExitStatus {
406 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407 write!(f, "exit code: {}", self.0)
411 fn zeroed_startupinfo() -> c::STARTUPINFO {
414 lpReserved: ptr::null_mut(),
415 lpDesktop: ptr::null_mut(),
416 lpTitle: ptr::null_mut(),
427 lpReserved2: ptr::null_mut(),
428 hStdInput: c::INVALID_HANDLE_VALUE,
429 hStdOutput: c::INVALID_HANDLE_VALUE,
430 hStdError: c::INVALID_HANDLE_VALUE,
434 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
435 c::PROCESS_INFORMATION {
436 hProcess: ptr::null_mut(),
437 hThread: ptr::null_mut(),
443 // Produces a wide string *without terminating null*; returns an error if
444 // `prog` or any of the `args` contain a nul.
445 fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> {
446 // Encode the command and arguments in a command line string such
447 // that the spawned process may recover them using CommandLineToArgvW.
448 let mut cmd: Vec<u16> = Vec::new();
449 // Always quote the program name so CreateProcess doesn't interpret args as
450 // part of the name if the binary wasn't found first time.
451 append_arg(&mut cmd, prog, true)?;
453 cmd.push(' ' as u16);
454 append_arg(&mut cmd, arg, false)?;
458 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr, force_quotes: bool) -> io::Result<()> {
459 // If an argument has 0 characters then we need to quote it to ensure
460 // that it actually gets passed through on the command line or otherwise
461 // it will be dropped entirely when parsed on the other end.
462 ensure_no_nuls(arg)?;
463 let arg_bytes = &arg.as_inner().inner.as_inner();
464 let quote = force_quotes || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
465 || arg_bytes.is_empty();
467 cmd.push('"' as u16);
470 let mut iter = arg.encode_wide();
471 let mut backslashes: usize = 0;
472 while let Some(x) = iter.next() {
473 if x == '\\' as u16 {
477 // Add n+1 backslashes to total 2n+1 before internal '"'.
478 for _ in 0..(backslashes+1) {
479 cmd.push('\\' as u16);
488 // Add n backslashes to total 2n before ending '"'.
489 for _ in 0..backslashes {
490 cmd.push('\\' as u16);
492 cmd.push('"' as u16);
498 fn make_envp(maybe_env: Option<BTreeMap<WindowsEnvKey, 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 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}\""