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};
22 use libc::{self, c_void};
24 use os::windows::ffi::OsStrExt;
27 use sync::{StaticMutex, MUTEX_INIT};
29 use sys::fs::{OpenOptions, File};
30 use sys::handle::Handle;
31 use sys::pipe::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()
48 pub program: OsString,
49 pub args: Vec<OsString>,
50 pub env: Option<HashMap<OsString, OsString>>,
51 pub cwd: Option<OsString>,
52 pub detach: bool, // not currently exposed in std::process
56 pub fn new(program: &OsStr) -> Command {
58 program: program.to_os_string(),
66 pub fn arg(&mut self, arg: &OsStr) {
67 self.args.push(arg.to_os_string())
69 pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
70 self.args.extend(args.map(OsStr::to_os_string))
72 fn init_env_map(&mut self){
73 if self.env.is_none() {
74 self.env = Some(env::vars_os().map(|(key, val)| {
79 pub fn env(&mut self, key: &OsStr, val: &OsStr) {
81 self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
83 pub fn env_remove(&mut self, key: &OsStr) {
85 self.env.as_mut().unwrap().remove(&mk_key(key));
87 pub fn env_clear(&mut self) {
88 self.env = Some(HashMap::new())
90 pub fn cwd(&mut self, dir: &OsStr) {
91 self.cwd = Some(dir.to_os_string())
95 ////////////////////////////////////////////////////////////////////////////////
97 ////////////////////////////////////////////////////////////////////////////////
99 /// A value representing a child process.
101 /// The lifetime of this value is linked to the lifetime of the actual
102 /// process - the Process destructor calls self.finish() which waits
103 /// for the process to terminate.
115 pub fn spawn(cfg: &Command,
118 err_handle: Stdio) -> io::Result<Process>
120 use libc::{TRUE, STARTF_USESTDHANDLES};
121 use libc::{DWORD, STARTUPINFO, CreateProcessW};
123 // To have the spawning semantics of unix/windows stay the same, we need
124 // to read the *child's* PATH if one is provided. See #15149 for more
126 let program = cfg.env.as_ref().and_then(|env| {
127 for (key, v) in env {
128 if OsStr::new("PATH") != &**key { continue }
130 // Split the value and test each path to see if the
132 for path in split_paths(&v) {
133 let path = path.join(cfg.program.to_str().unwrap())
134 .with_extension(env::consts::EXE_EXTENSION);
135 if fs::metadata(&path).is_ok() {
136 return Some(path.into_os_string())
144 let mut si = zeroed_startupinfo();
145 si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
146 si.dwFlags = STARTF_USESTDHANDLES;
148 let stdin = try!(in_handle.to_handle(c::STD_INPUT_HANDLE));
149 let stdout = try!(out_handle.to_handle(c::STD_OUTPUT_HANDLE));
150 let stderr = try!(err_handle.to_handle(c::STD_ERROR_HANDLE));
152 si.hStdInput = stdin.raw();
153 si.hStdOutput = stdout.raw();
154 si.hStdError = stderr.raw();
156 let program = program.as_ref().unwrap_or(&cfg.program);
157 let mut cmd_str = make_command_line(program, &cfg.args);
158 cmd_str.push(0); // add null terminator
160 // stolen from the libuv code.
161 let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
163 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
166 let (envp, _data) = make_envp(cfg.env.as_ref());
167 let (dirp, _data) = make_dirp(cfg.cwd.as_ref());
168 let mut pi = zeroed_process_information();
170 // `CreateProcess` is racy!
171 // http://support.microsoft.com/kb/315939
172 static CREATE_PROCESS_LOCK: StaticMutex = MUTEX_INIT;
173 let _lock = CREATE_PROCESS_LOCK.lock();
175 cvt(CreateProcessW(ptr::null(),
176 cmd_str.as_mut_ptr(),
179 TRUE, flags, envp, dirp,
183 // We close the thread handle because we don't care about keeping
184 // the thread id valid, and we aren't keeping the thread handle
185 // around to be able to close it later.
186 drop(Handle::new(pi.hThread));
188 Ok(Process { handle: Handle::new(pi.hProcess) })
191 pub unsafe fn kill(&self) -> io::Result<()> {
192 try!(cvt(libc::TerminateProcess(self.handle.raw(), 1)));
196 pub fn wait(&self) -> io::Result<ExitStatus> {
197 use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0};
198 use libc::{GetExitCodeProcess, WaitForSingleObject};
203 try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status)));
204 if status != STILL_ACTIVE {
205 return Ok(ExitStatus(status as i32));
207 match WaitForSingleObject(self.handle.raw(), INFINITE) {
209 _ => return Err(Error::last_os_error()),
216 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
217 pub struct ExitStatus(i32);
220 pub fn success(&self) -> bool {
223 pub fn code(&self) -> Option<i32> {
228 impl fmt::Display for ExitStatus {
229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230 write!(f, "exit code: {}", self.0)
234 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
235 libc::types::os::arch::extra::STARTUPINFO {
237 lpReserved: ptr::null_mut(),
238 lpDesktop: ptr::null_mut(),
239 lpTitle: ptr::null_mut(),
250 lpReserved2: ptr::null_mut(),
251 hStdInput: libc::INVALID_HANDLE_VALUE,
252 hStdOutput: libc::INVALID_HANDLE_VALUE,
253 hStdError: libc::INVALID_HANDLE_VALUE,
257 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
258 libc::types::os::arch::extra::PROCESS_INFORMATION {
259 hProcess: ptr::null_mut(),
260 hThread: ptr::null_mut(),
266 // Produces a wide string *without terminating null*
267 fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> {
268 // Encode the command and arguments in a command line string such
269 // that the spawned process may recover them using CommandLineToArgvW.
270 let mut cmd: Vec<u16> = Vec::new();
271 append_arg(&mut cmd, prog);
273 cmd.push(' ' as u16);
274 append_arg(&mut cmd, arg);
278 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) {
279 // If an argument has 0 characters then we need to quote it to ensure
280 // that it actually gets passed through on the command line or otherwise
281 // it will be dropped entirely when parsed on the other end.
282 let arg_bytes = &arg.as_inner().inner.as_inner();
283 let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
284 || arg_bytes.is_empty();
286 cmd.push('"' as u16);
289 let mut iter = arg.encode_wide();
290 let mut backslashes: usize = 0;
291 while let Some(x) = iter.next() {
292 if x == '\\' as u16 {
296 // Add n+1 backslashes to total 2n+1 before internal '"'.
297 for _ in 0..(backslashes+1) {
298 cmd.push('\\' as u16);
307 // Add n backslashes to total 2n before ending '"'.
308 for _ in 0..backslashes {
309 cmd.push('\\' as u16);
311 cmd.push('"' as u16);
316 fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
317 -> (*mut c_void, Vec<u16>) {
318 // On Windows we pass an "environment block" which is not a char**, but
319 // rather a concatenation of null-terminated k=v\0 sequences, with a final
323 let mut blk = Vec::new();
326 blk.extend(pair.0.encode_wide());
327 blk.push('=' as u16);
328 blk.extend(pair.1.encode_wide());
332 (blk.as_mut_ptr() as *mut c_void, blk)
334 _ => (ptr::null_mut(), Vec::new())
338 fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) {
341 let mut dir_str: Vec<u16> = dir.encode_wide().collect();
343 (dir_str.as_ptr(), dir_str)
345 None => (ptr::null(), Vec::new())
350 fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> {
351 use libc::DUPLICATE_SAME_ACCESS;
355 stdio::get(stdio_id).and_then(|io| {
356 io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
359 Stdio::Piped(ref pipe) => {
360 pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
363 // Similarly to unix, we don't actually leave holes for the
364 // stdio file descriptors, but rather open up /dev/null
365 // equivalents. These equivalents are drawn from libuv's
366 // windows process spawning.
368 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
369 let mut sa = libc::SECURITY_ATTRIBUTES {
370 nLength: size as libc::DWORD,
371 lpSecurityDescriptor: ptr::null_mut(),
374 let mut opts = OpenOptions::new();
375 opts.read(stdio_id == c::STD_INPUT_HANDLE);
376 opts.write(stdio_id != c::STD_INPUT_HANDLE);
377 opts.security_attributes(&mut sa);
378 File::open(Path::new("NUL"), &opts).map(|file| {
390 use ffi::{OsStr, OsString};
391 use super::make_command_line;
394 fn test_make_command_line() {
395 fn test_wrapper(prog: &str, args: &[&str]) -> String {
397 &make_command_line(OsStr::new(prog),
399 .map(|a| OsString::from(a))
400 .collect::<Vec<OsString>>())).unwrap()
404 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
409 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
410 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
413 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
414 "\"C:\\Program Files\\test\" aa\\\"bb"
417 test_wrapper("echo", &["a b c"]),
421 test_wrapper("echo", &["\" \\\" \\", "\\"]),
422 "echo \"\\\" \\\\\\\" \\\\\" \\"
425 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
426 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"