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.
14 use collections::HashMap;
18 use ffi::{OsString, OsStr};
21 use io::{self, Error, ErrorKind};
24 use os::windows::ffi::OsStrExt;
27 use sys::mutex::Mutex;
29 use sys::fs::{OpenOptions, File};
30 use sys::handle::Handle;
31 use sys::pipe::{self, AnonPipe};
34 use sys_common::{AsInner, FromInner};
36 ////////////////////////////////////////////////////////////////////////////////
38 ////////////////////////////////////////////////////////////////////////////////
40 fn mk_key(s: &OsStr) -> OsString {
41 FromInner::from_inner(sys::os_str::Buf {
42 inner: s.as_inner().inner.to_ascii_uppercase()
46 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
47 if str.as_ref().encode_wide().any(|b| b == 0) {
48 Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"))
57 env: Option<HashMap<OsString, OsString>>,
58 cwd: Option<OsString>,
59 detach: bool, // not currently exposed in std::process
61 stdout: Option<Stdio>,
62 stderr: Option<Stdio>,
72 pub struct StdioPipes {
73 pub stdin: Option<AnonPipe>,
74 pub stdout: Option<AnonPipe>,
75 pub stderr: Option<AnonPipe>,
78 struct DropGuard<'a> {
83 pub fn new(program: &OsStr) -> Command {
85 program: program.to_os_string(),
96 pub fn arg(&mut self, arg: &OsStr) {
97 self.args.push(arg.to_os_string())
99 fn init_env_map(&mut self){
100 if self.env.is_none() {
101 self.env = Some(env::vars_os().map(|(key, val)| {
106 pub fn env(&mut self, key: &OsStr, val: &OsStr) {
108 self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
110 pub fn env_remove(&mut self, key: &OsStr) {
112 self.env.as_mut().unwrap().remove(&mk_key(key));
114 pub fn env_clear(&mut self) {
115 self.env = Some(HashMap::new())
117 pub fn cwd(&mut self, dir: &OsStr) {
118 self.cwd = Some(dir.to_os_string())
120 pub fn stdin(&mut self, stdin: Stdio) {
121 self.stdin = Some(stdin);
123 pub fn stdout(&mut self, stdout: Stdio) {
124 self.stdout = Some(stdout);
126 pub fn stderr(&mut self, stderr: Stdio) {
127 self.stderr = Some(stderr);
130 pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
131 -> io::Result<(Process, StdioPipes)> {
132 // To have the spawning semantics of unix/windows stay the same, we need
133 // to read the *child's* PATH if one is provided. See #15149 for more
135 let program = self.env.as_ref().and_then(|env| {
136 for (key, v) in env {
137 if OsStr::new("PATH") != &**key { continue }
139 // Split the value and test each path to see if the
141 for path in split_paths(&v) {
142 let path = path.join(self.program.to_str().unwrap())
143 .with_extension(env::consts::EXE_EXTENSION);
144 if fs::metadata(&path).is_ok() {
145 return Some(path.into_os_string())
153 let mut si = zeroed_startupinfo();
154 si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
155 si.dwFlags = c::STARTF_USESTDHANDLES;
157 let program = program.as_ref().unwrap_or(&self.program);
158 let mut cmd_str = make_command_line(program, &self.args)?;
159 cmd_str.push(0); // add null terminator
161 // stolen from the libuv code.
162 let mut flags = c::CREATE_UNICODE_ENVIRONMENT;
164 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
167 let (envp, _data) = make_envp(self.env.as_ref())?;
168 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
169 let mut pi = zeroed_process_information();
171 // Prepare all stdio handles to be inherited by the child. This
172 // currently involves duplicating any existing ones with the ability to
173 // be inherited by child processes. Note, however, that once an
174 // inheritable handle is created, *any* spawned child will inherit that
175 // handle. We only want our own child to inherit this handle, so we wrap
176 // the remaining portion of this spawn in a mutex.
178 // For more information, msdn also has an article about this race:
179 // http://support.microsoft.com/kb/315939
180 static CREATE_PROCESS_LOCK: Mutex = Mutex::new();
181 let _guard = DropGuard::new(&CREATE_PROCESS_LOCK);
183 let mut pipes = StdioPipes {
188 let null = Stdio::Null;
189 let default_stdin = if needs_stdin {&default} else {&null};
190 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
191 let stdout = self.stdout.as_ref().unwrap_or(&default);
192 let stderr = self.stderr.as_ref().unwrap_or(&default);
193 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
194 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE,
196 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
198 si.hStdInput = stdin.raw();
199 si.hStdOutput = stdout.raw();
200 si.hStdError = stderr.raw();
203 cvt(c::CreateProcessW(ptr::null(),
204 cmd_str.as_mut_ptr(),
207 c::TRUE, flags, envp, dirp,
211 // We close the thread handle because we don't care about keeping
212 // the thread id valid, and we aren't keeping the thread handle
213 // around to be able to close it later.
214 drop(Handle::new(pi.hThread));
216 Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
221 impl fmt::Debug for Command {
222 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 write!(f, "{:?}", self.program)?;
224 for arg in &self.args {
225 write!(f, " {:?}", arg)?;
231 impl<'a> DropGuard<'a> {
232 fn new(lock: &'a Mutex) -> DropGuard<'a> {
235 DropGuard { lock: lock }
240 impl<'a> Drop for DropGuard<'a> {
249 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
250 -> io::Result<Handle> {
252 // If no stdio handle is available, then inherit means that it
253 // should still be unavailable so propagate the
254 // INVALID_HANDLE_VALUE.
256 match stdio::get(stdio_id) {
257 Ok(io) => io.handle().duplicate(0, true,
258 c::DUPLICATE_SAME_ACCESS),
259 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
264 let (reader, writer) = pipe::anon_pipe()?;
265 let (ours, theirs) = if stdio_id == c::STD_INPUT_HANDLE {
272 c::SetHandleInformation(theirs.handle().raw(),
273 c::HANDLE_FLAG_INHERIT,
274 c::HANDLE_FLAG_INHERIT)
276 Ok(theirs.into_handle())
279 Stdio::Handle(ref handle) => {
280 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
283 // Open up a reference to NUL with appropriate read/write
284 // permissions as well as the ability to be inherited to child
285 // processes (as this is about to be inherited).
287 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
288 let mut sa = c::SECURITY_ATTRIBUTES {
289 nLength: size as c::DWORD,
290 lpSecurityDescriptor: ptr::null_mut(),
293 let mut opts = OpenOptions::new();
294 opts.read(stdio_id == c::STD_INPUT_HANDLE);
295 opts.write(stdio_id != c::STD_INPUT_HANDLE);
296 opts.security_attributes(&mut sa);
297 File::open(Path::new("NUL"), &opts).map(|file| {
305 ////////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////////////////////////////////////////////////////
309 /// A value representing a child process.
311 /// The lifetime of this value is linked to the lifetime of the actual
312 /// process - the Process destructor calls self.finish() which waits
313 /// for the process to terminate.
319 pub fn kill(&mut self) -> io::Result<()> {
321 c::TerminateProcess(self.handle.raw(), 1)
326 pub fn id(&self) -> u32 {
328 c::GetProcessId(self.handle.raw()) as u32
332 pub fn wait(&mut self) -> io::Result<ExitStatus> {
334 let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
335 if res != c::WAIT_OBJECT_0 {
336 return Err(Error::last_os_error())
339 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
340 Ok(ExitStatus(status))
344 pub fn handle(&self) -> &Handle { &self.handle }
346 pub fn into_handle(self) -> Handle { self.handle }
349 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
350 pub struct ExitStatus(c::DWORD);
353 pub fn success(&self) -> bool {
356 pub fn code(&self) -> Option<i32> {
361 impl From<c::DWORD> for ExitStatus {
362 fn from(u: c::DWORD) -> ExitStatus {
367 impl fmt::Display for ExitStatus {
368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369 write!(f, "exit code: {}", self.0)
373 fn zeroed_startupinfo() -> c::STARTUPINFO {
376 lpReserved: ptr::null_mut(),
377 lpDesktop: ptr::null_mut(),
378 lpTitle: ptr::null_mut(),
389 lpReserved2: ptr::null_mut(),
390 hStdInput: c::INVALID_HANDLE_VALUE,
391 hStdOutput: c::INVALID_HANDLE_VALUE,
392 hStdError: c::INVALID_HANDLE_VALUE,
396 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
397 c::PROCESS_INFORMATION {
398 hProcess: ptr::null_mut(),
399 hThread: ptr::null_mut(),
405 // Produces a wide string *without terminating null*; returns an error if
406 // `prog` or any of the `args` contain a nul.
407 fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> {
408 // Encode the command and arguments in a command line string such
409 // that the spawned process may recover them using CommandLineToArgvW.
410 let mut cmd: Vec<u16> = Vec::new();
411 append_arg(&mut cmd, prog)?;
413 cmd.push(' ' as u16);
414 append_arg(&mut cmd, arg)?;
418 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) -> io::Result<()> {
419 // If an argument has 0 characters then we need to quote it to ensure
420 // that it actually gets passed through on the command line or otherwise
421 // it will be dropped entirely when parsed on the other end.
422 ensure_no_nuls(arg)?;
423 let arg_bytes = &arg.as_inner().inner.as_inner();
424 let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
425 || arg_bytes.is_empty();
427 cmd.push('"' as u16);
430 let mut iter = arg.encode_wide();
431 let mut backslashes: usize = 0;
432 while let Some(x) = iter.next() {
433 if x == '\\' as u16 {
437 // Add n+1 backslashes to total 2n+1 before internal '"'.
438 for _ in 0..(backslashes+1) {
439 cmd.push('\\' as u16);
448 // Add n backslashes to total 2n before ending '"'.
449 for _ in 0..backslashes {
450 cmd.push('\\' as u16);
452 cmd.push('"' as u16);
458 fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
459 -> io::Result<(*mut c_void, Vec<u16>)> {
460 // On Windows we pass an "environment block" which is not a char**, but
461 // rather a concatenation of null-terminated k=v\0 sequences, with a final
465 let mut blk = Vec::new();
468 blk.extend(ensure_no_nuls(pair.0)?.encode_wide());
469 blk.push('=' as u16);
470 blk.extend(ensure_no_nuls(pair.1)?.encode_wide());
474 Ok((blk.as_mut_ptr() as *mut c_void, blk))
476 _ => Ok((ptr::null_mut(), Vec::new()))
480 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
484 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
486 Ok((dir_str.as_ptr(), dir_str))
488 None => Ok((ptr::null(), Vec::new()))
495 use ffi::{OsStr, OsString};
496 use super::make_command_line;
499 fn test_make_command_line() {
500 fn test_wrapper(prog: &str, args: &[&str]) -> String {
501 let command_line = &make_command_line(OsStr::new(prog),
503 .map(|a| OsString::from(a))
504 .collect::<Vec<OsString>>())
506 String::from_utf16(command_line).unwrap()
510 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
515 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
516 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
519 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
520 "\"C:\\Program Files\\test\" aa\\\"bb"
523 test_wrapper("echo", &["a b c"]),
527 test_wrapper("echo", &["\" \\\" \\", "\\"]),
528 "echo \"\\\" \\\\\\\" \\\\\" \\"
531 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
532 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"