]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/windows/process.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libstd / sys / windows / process.rs
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.
4 //
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.
10
11 use prelude::v1::*;
12
13 use ascii::*;
14 use collections::HashMap;
15 use collections;
16 use env::split_paths;
17 use env;
18 use ffi::{OsString, OsStr};
19 use fmt;
20 use fs;
21 use io::{self, Error, ErrorKind};
22 use libc::c_void;
23 use mem;
24 use os::windows::ffi::OsStrExt;
25 use path::Path;
26 use ptr;
27 use sync::StaticMutex;
28 use sys::c;
29 use sys::fs::{OpenOptions, File};
30 use sys::handle::Handle;
31 use sys::pipe::{self, AnonPipe};
32 use sys::stdio;
33 use sys::{self, cvt};
34 use sys_common::{AsInner, FromInner};
35
36 ////////////////////////////////////////////////////////////////////////////////
37 // Command
38 ////////////////////////////////////////////////////////////////////////////////
39
40 fn mk_key(s: &OsStr) -> OsString {
41 FromInner::from_inner(sys::os_str::Buf {
42 inner: s.as_inner().inner.to_ascii_uppercase()
43 })
44 }
45
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"))
49 } else {
50 Ok(str)
51 }
52 }
53
54 pub struct Command {
55 program: OsString,
56 args: Vec<OsString>,
57 env: Option<HashMap<OsString, OsString>>,
58 cwd: Option<OsString>,
59 detach: bool, // not currently exposed in std::process
60 stdin: Option<Stdio>,
61 stdout: Option<Stdio>,
62 stderr: Option<Stdio>,
63 }
64
65 pub enum Stdio {
66 Inherit,
67 Null,
68 MakePipe,
69 Handle(Handle),
70 }
71
72 pub struct StdioPipes {
73 pub stdin: Option<AnonPipe>,
74 pub stdout: Option<AnonPipe>,
75 pub stderr: Option<AnonPipe>,
76 }
77
78 impl Command {
79 pub fn new(program: &OsStr) -> Command {
80 Command {
81 program: program.to_os_string(),
82 args: Vec::new(),
83 env: None,
84 cwd: None,
85 detach: false,
86 stdin: None,
87 stdout: None,
88 stderr: None,
89 }
90 }
91
92 pub fn arg(&mut self, arg: &OsStr) {
93 self.args.push(arg.to_os_string())
94 }
95 fn init_env_map(&mut self){
96 if self.env.is_none() {
97 self.env = Some(env::vars_os().map(|(key, val)| {
98 (mk_key(&key), val)
99 }).collect());
100 }
101 }
102 pub fn env(&mut self, key: &OsStr, val: &OsStr) {
103 self.init_env_map();
104 self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
105 }
106 pub fn env_remove(&mut self, key: &OsStr) {
107 self.init_env_map();
108 self.env.as_mut().unwrap().remove(&mk_key(key));
109 }
110 pub fn env_clear(&mut self) {
111 self.env = Some(HashMap::new())
112 }
113 pub fn cwd(&mut self, dir: &OsStr) {
114 self.cwd = Some(dir.to_os_string())
115 }
116 pub fn stdin(&mut self, stdin: Stdio) {
117 self.stdin = Some(stdin);
118 }
119 pub fn stdout(&mut self, stdout: Stdio) {
120 self.stdout = Some(stdout);
121 }
122 pub fn stderr(&mut self, stderr: Stdio) {
123 self.stderr = Some(stderr);
124 }
125
126 pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
127 -> io::Result<(Process, StdioPipes)> {
128 // To have the spawning semantics of unix/windows stay the same, we need
129 // to read the *child's* PATH if one is provided. See #15149 for more
130 // details.
131 let program = self.env.as_ref().and_then(|env| {
132 for (key, v) in env {
133 if OsStr::new("PATH") != &**key { continue }
134
135 // Split the value and test each path to see if the
136 // program exists.
137 for path in split_paths(&v) {
138 let path = path.join(self.program.to_str().unwrap())
139 .with_extension(env::consts::EXE_EXTENSION);
140 if fs::metadata(&path).is_ok() {
141 return Some(path.into_os_string())
142 }
143 }
144 break
145 }
146 None
147 });
148
149 let mut si = zeroed_startupinfo();
150 si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
151 si.dwFlags = c::STARTF_USESTDHANDLES;
152
153 let program = program.as_ref().unwrap_or(&self.program);
154 let mut cmd_str = make_command_line(program, &self.args)?;
155 cmd_str.push(0); // add null terminator
156
157 // stolen from the libuv code.
158 let mut flags = c::CREATE_UNICODE_ENVIRONMENT;
159 if self.detach {
160 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
161 }
162
163 let (envp, _data) = make_envp(self.env.as_ref())?;
164 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
165 let mut pi = zeroed_process_information();
166
167 // Prepare all stdio handles to be inherited by the child. This
168 // currently involves duplicating any existing ones with the ability to
169 // be inherited by child processes. Note, however, that once an
170 // inheritable handle is created, *any* spawned child will inherit that
171 // handle. We only want our own child to inherit this handle, so we wrap
172 // the remaining portion of this spawn in a mutex.
173 //
174 // For more information, msdn also has an article about this race:
175 // http://support.microsoft.com/kb/315939
176 static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
177 let _lock = CREATE_PROCESS_LOCK.lock();
178
179 let mut pipes = StdioPipes {
180 stdin: None,
181 stdout: None,
182 stderr: None,
183 };
184 let null = Stdio::Null;
185 let default_stdin = if needs_stdin {&default} else {&null};
186 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
187 let stdout = self.stdout.as_ref().unwrap_or(&default);
188 let stderr = self.stderr.as_ref().unwrap_or(&default);
189 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
190 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE,
191 &mut pipes.stdout)?;
192 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
193 &mut pipes.stderr)?;
194 si.hStdInput = stdin.raw();
195 si.hStdOutput = stdout.raw();
196 si.hStdError = stderr.raw();
197
198 unsafe {
199 cvt(c::CreateProcessW(ptr::null(),
200 cmd_str.as_mut_ptr(),
201 ptr::null_mut(),
202 ptr::null_mut(),
203 c::TRUE, flags, envp, dirp,
204 &mut si, &mut pi))
205 }?;
206
207 // We close the thread handle because we don't care about keeping
208 // the thread id valid, and we aren't keeping the thread handle
209 // around to be able to close it later.
210 drop(Handle::new(pi.hThread));
211
212 Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
213 }
214
215 }
216
217 impl fmt::Debug for Command {
218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 write!(f, "{:?}", self.program)?;
220 for arg in &self.args {
221 write!(f, " {:?}", arg)?;
222 }
223 Ok(())
224 }
225 }
226
227 impl Stdio {
228 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
229 -> io::Result<Handle> {
230 match *self {
231 // If no stdio handle is available, then inherit means that it
232 // should still be unavailable so propagate the
233 // INVALID_HANDLE_VALUE.
234 Stdio::Inherit => {
235 match stdio::get(stdio_id) {
236 Ok(io) => io.handle().duplicate(0, true,
237 c::DUPLICATE_SAME_ACCESS),
238 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
239 }
240 }
241
242 Stdio::MakePipe => {
243 let (reader, writer) = pipe::anon_pipe()?;
244 let (ours, theirs) = if stdio_id == c::STD_INPUT_HANDLE {
245 (writer, reader)
246 } else {
247 (reader, writer)
248 };
249 *pipe = Some(ours);
250 cvt(unsafe {
251 c::SetHandleInformation(theirs.handle().raw(),
252 c::HANDLE_FLAG_INHERIT,
253 c::HANDLE_FLAG_INHERIT)
254 })?;
255 Ok(theirs.into_handle())
256 }
257
258 Stdio::Handle(ref handle) => {
259 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
260 }
261
262 // Open up a reference to NUL with appropriate read/write
263 // permissions as well as the ability to be inherited to child
264 // processes (as this is about to be inherited).
265 Stdio::Null => {
266 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
267 let mut sa = c::SECURITY_ATTRIBUTES {
268 nLength: size as c::DWORD,
269 lpSecurityDescriptor: ptr::null_mut(),
270 bInheritHandle: 1,
271 };
272 let mut opts = OpenOptions::new();
273 opts.read(stdio_id == c::STD_INPUT_HANDLE);
274 opts.write(stdio_id != c::STD_INPUT_HANDLE);
275 opts.security_attributes(&mut sa);
276 File::open(Path::new("NUL"), &opts).map(|file| {
277 file.into_handle()
278 })
279 }
280 }
281 }
282 }
283
284 ////////////////////////////////////////////////////////////////////////////////
285 // Processes
286 ////////////////////////////////////////////////////////////////////////////////
287
288 /// A value representing a child process.
289 ///
290 /// The lifetime of this value is linked to the lifetime of the actual
291 /// process - the Process destructor calls self.finish() which waits
292 /// for the process to terminate.
293 pub struct Process {
294 handle: Handle,
295 }
296
297 impl Process {
298 pub fn kill(&mut self) -> io::Result<()> {
299 cvt(unsafe {
300 c::TerminateProcess(self.handle.raw(), 1)
301 })?;
302 Ok(())
303 }
304
305 pub fn id(&self) -> u32 {
306 unsafe {
307 c::GetProcessId(self.handle.raw()) as u32
308 }
309 }
310
311 pub fn wait(&mut self) -> io::Result<ExitStatus> {
312 unsafe {
313 let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
314 if res != c::WAIT_OBJECT_0 {
315 return Err(Error::last_os_error())
316 }
317 let mut status = 0;
318 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
319 Ok(ExitStatus(status))
320 }
321 }
322
323 pub fn handle(&self) -> &Handle { &self.handle }
324
325 pub fn into_handle(self) -> Handle { self.handle }
326 }
327
328 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
329 pub struct ExitStatus(c::DWORD);
330
331 impl ExitStatus {
332 pub fn success(&self) -> bool {
333 self.0 == 0
334 }
335 pub fn code(&self) -> Option<i32> {
336 Some(self.0 as i32)
337 }
338 }
339
340 impl fmt::Display for ExitStatus {
341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
342 write!(f, "exit code: {}", self.0)
343 }
344 }
345
346 fn zeroed_startupinfo() -> c::STARTUPINFO {
347 c::STARTUPINFO {
348 cb: 0,
349 lpReserved: ptr::null_mut(),
350 lpDesktop: ptr::null_mut(),
351 lpTitle: ptr::null_mut(),
352 dwX: 0,
353 dwY: 0,
354 dwXSize: 0,
355 dwYSize: 0,
356 dwXCountChars: 0,
357 dwYCountCharts: 0,
358 dwFillAttribute: 0,
359 dwFlags: 0,
360 wShowWindow: 0,
361 cbReserved2: 0,
362 lpReserved2: ptr::null_mut(),
363 hStdInput: c::INVALID_HANDLE_VALUE,
364 hStdOutput: c::INVALID_HANDLE_VALUE,
365 hStdError: c::INVALID_HANDLE_VALUE,
366 }
367 }
368
369 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
370 c::PROCESS_INFORMATION {
371 hProcess: ptr::null_mut(),
372 hThread: ptr::null_mut(),
373 dwProcessId: 0,
374 dwThreadId: 0
375 }
376 }
377
378 // Produces a wide string *without terminating null*; returns an error if
379 // `prog` or any of the `args` contain a nul.
380 fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> {
381 // Encode the command and arguments in a command line string such
382 // that the spawned process may recover them using CommandLineToArgvW.
383 let mut cmd: Vec<u16> = Vec::new();
384 append_arg(&mut cmd, prog)?;
385 for arg in args {
386 cmd.push(' ' as u16);
387 append_arg(&mut cmd, arg)?;
388 }
389 return Ok(cmd);
390
391 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) -> io::Result<()> {
392 // If an argument has 0 characters then we need to quote it to ensure
393 // that it actually gets passed through on the command line or otherwise
394 // it will be dropped entirely when parsed on the other end.
395 ensure_no_nuls(arg)?;
396 let arg_bytes = &arg.as_inner().inner.as_inner();
397 let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
398 || arg_bytes.is_empty();
399 if quote {
400 cmd.push('"' as u16);
401 }
402
403 let mut iter = arg.encode_wide();
404 let mut backslashes: usize = 0;
405 while let Some(x) = iter.next() {
406 if x == '\\' as u16 {
407 backslashes += 1;
408 } else {
409 if x == '"' as u16 {
410 // Add n+1 backslashes to total 2n+1 before internal '"'.
411 for _ in 0..(backslashes+1) {
412 cmd.push('\\' as u16);
413 }
414 }
415 backslashes = 0;
416 }
417 cmd.push(x);
418 }
419
420 if quote {
421 // Add n backslashes to total 2n before ending '"'.
422 for _ in 0..backslashes {
423 cmd.push('\\' as u16);
424 }
425 cmd.push('"' as u16);
426 }
427 Ok(())
428 }
429 }
430
431 fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
432 -> io::Result<(*mut c_void, Vec<u16>)> {
433 // On Windows we pass an "environment block" which is not a char**, but
434 // rather a concatenation of null-terminated k=v\0 sequences, with a final
435 // \0 to terminate.
436 match env {
437 Some(env) => {
438 let mut blk = Vec::new();
439
440 for pair in env {
441 blk.extend(ensure_no_nuls(pair.0)?.encode_wide());
442 blk.push('=' as u16);
443 blk.extend(ensure_no_nuls(pair.1)?.encode_wide());
444 blk.push(0);
445 }
446 blk.push(0);
447 Ok((blk.as_mut_ptr() as *mut c_void, blk))
448 }
449 _ => Ok((ptr::null_mut(), Vec::new()))
450 }
451 }
452
453 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
454
455 match d {
456 Some(dir) => {
457 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
458 dir_str.push(0);
459 Ok((dir_str.as_ptr(), dir_str))
460 },
461 None => Ok((ptr::null(), Vec::new()))
462 }
463 }
464
465 #[cfg(test)]
466 mod tests {
467 use prelude::v1::*;
468 use ffi::{OsStr, OsString};
469 use super::make_command_line;
470
471 #[test]
472 fn test_make_command_line() {
473 fn test_wrapper(prog: &str, args: &[&str]) -> String {
474 let command_line = &make_command_line(OsStr::new(prog),
475 &args.iter()
476 .map(|a| OsString::from(a))
477 .collect::<Vec<OsString>>())
478 .unwrap();
479 String::from_utf16(command_line).unwrap()
480 }
481
482 assert_eq!(
483 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
484 "prog aaa bbb ccc"
485 );
486
487 assert_eq!(
488 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
489 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
490 );
491 assert_eq!(
492 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
493 "\"C:\\Program Files\\test\" aa\\\"bb"
494 );
495 assert_eq!(
496 test_wrapper("echo", &["a b c"]),
497 "echo \"a b c\""
498 );
499 assert_eq!(
500 test_wrapper("echo", &["\" \\\" \\", "\\"]),
501 "echo \"\\\" \\\\\\\" \\\\\" \\"
502 );
503 assert_eq!(
504 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
505 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
506 );
507 }
508 }