]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
Refactor away `inferred_obligations` from the trait selector
[rust.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 #![unstable(feature = "process_internals", issue = "0")]
12
13 use ascii::AsciiExt;
14 use collections::BTreeMap;
15 use env::split_paths;
16 use env;
17 use ffi::{OsString, OsStr};
18 use fmt;
19 use fs;
20 use io::{self, Error, ErrorKind};
21 use libc::c_void;
22 use mem;
23 use os::windows::ffi::OsStrExt;
24 use path::Path;
25 use ptr;
26 use sys::mutex::Mutex;
27 use sys::c;
28 use sys::fs::{OpenOptions, File};
29 use sys::handle::Handle;
30 use sys::pipe::{self, AnonPipe};
31 use sys::stdio;
32 use sys::cvt;
33 use sys_common::{AsInner, FromInner, IntoInner};
34 use sys_common::process::{CommandEnv, EnvKey};
35 use alloc::borrow::Borrow;
36
37 ////////////////////////////////////////////////////////////////////////////////
38 // Command
39 ////////////////////////////////////////////////////////////////////////////////
40
41 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
42 #[doc(hidden)]
43 pub struct WindowsEnvKey(OsString);
44
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)))
50     }
51 }
52
53 impl From<WindowsEnvKey> for OsString {
54     fn from(k: WindowsEnvKey) -> Self { k.0 }
55 }
56
57 impl Borrow<OsStr> for WindowsEnvKey {
58     fn borrow(&self) -> &OsStr { &self.0 }
59 }
60
61 impl AsRef<OsStr> for WindowsEnvKey {
62     fn as_ref(&self) -> &OsStr { &self.0 }
63 }
64
65 impl EnvKey for WindowsEnvKey {}
66
67
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"))
71     } else {
72         Ok(str)
73     }
74 }
75
76 pub struct Command {
77     program: OsString,
78     args: Vec<OsString>,
79     env: CommandEnv<WindowsEnvKey>,
80     cwd: Option<OsString>,
81     flags: u32,
82     detach: bool, // not currently exposed in std::process
83     stdin: Option<Stdio>,
84     stdout: Option<Stdio>,
85     stderr: Option<Stdio>,
86 }
87
88 pub enum Stdio {
89     Inherit,
90     Null,
91     MakePipe,
92     Handle(Handle),
93 }
94
95 pub struct StdioPipes {
96     pub stdin: Option<AnonPipe>,
97     pub stdout: Option<AnonPipe>,
98     pub stderr: Option<AnonPipe>,
99 }
100
101 struct DropGuard<'a> {
102     lock: &'a Mutex,
103 }
104
105 impl Command {
106     pub fn new(program: &OsStr) -> Command {
107         Command {
108             program: program.to_os_string(),
109             args: Vec::new(),
110             env: Default::default(),
111             cwd: None,
112             flags: 0,
113             detach: false,
114             stdin: None,
115             stdout: None,
116             stderr: None,
117         }
118     }
119
120     pub fn arg(&mut self, arg: &OsStr) {
121         self.args.push(arg.to_os_string())
122     }
123     pub fn env_mut(&mut self) -> &mut CommandEnv<WindowsEnvKey> {
124         &mut self.env
125     }
126     pub fn cwd(&mut self, dir: &OsStr) {
127         self.cwd = Some(dir.to_os_string())
128     }
129     pub fn stdin(&mut self, stdin: Stdio) {
130         self.stdin = Some(stdin);
131     }
132     pub fn stdout(&mut self, stdout: Stdio) {
133         self.stdout = Some(stdout);
134     }
135     pub fn stderr(&mut self, stderr: Stdio) {
136         self.stderr = Some(stderr);
137     }
138     pub fn creation_flags(&mut self, flags: u32) {
139         self.flags = flags;
140     }
141
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
147         // details.
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
151                 // program exists.
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())
157                     }
158                 }
159             }
160             None
161         });
162
163         let mut si = zeroed_startupinfo();
164         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
165         si.dwFlags = c::STARTF_USESTDHANDLES;
166
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
170
171         // stolen from the libuv code.
172         let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
173         if self.detach {
174             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
175         }
176
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();
180
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.
187         //
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);
192
193         let mut pipes = StdioPipes {
194             stdin: None,
195             stdout: None,
196             stderr: None,
197         };
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,
205                                       &mut pipes.stdout)?;
206         let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
207                                       &mut pipes.stderr)?;
208         si.hStdInput = stdin.raw();
209         si.hStdOutput = stdout.raw();
210         si.hStdError = stderr.raw();
211
212         unsafe {
213             cvt(c::CreateProcessW(ptr::null(),
214                                   cmd_str.as_mut_ptr(),
215                                   ptr::null_mut(),
216                                   ptr::null_mut(),
217                                   c::TRUE, flags, envp, dirp,
218                                   &mut si, &mut pi))
219         }?;
220
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));
225
226         Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
227     }
228
229 }
230
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)?;
236         }
237         Ok(())
238     }
239 }
240
241 impl<'a> DropGuard<'a> {
242     fn new(lock: &'a Mutex) -> DropGuard<'a> {
243         unsafe {
244             lock.lock();
245             DropGuard { lock: lock }
246         }
247     }
248 }
249
250 impl<'a> Drop for DropGuard<'a> {
251     fn drop(&mut self) {
252         unsafe {
253             self.lock.unlock();
254         }
255     }
256 }
257
258 impl Stdio {
259     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
260                  -> io::Result<Handle> {
261         match *self {
262             // If no stdio handle is available, then inherit means that it
263             // should still be unavailable so propagate the
264             // INVALID_HANDLE_VALUE.
265             Stdio::Inherit => {
266                 match stdio::get(stdio_id) {
267                     Ok(io) => {
268                         let io = Handle::new(io.handle());
269                         let ret = io.duplicate(0, true,
270                                                c::DUPLICATE_SAME_ACCESS);
271                         io.into_raw();
272                         return ret
273                     }
274                     Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
275                 }
276             }
277
278             Stdio::MakePipe => {
279                 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
280                 let pipes = pipe::anon_pipe(ours_readable)?;
281                 *pipe = Some(pipes.ours);
282                 cvt(unsafe {
283                     c::SetHandleInformation(pipes.theirs.handle().raw(),
284                                             c::HANDLE_FLAG_INHERIT,
285                                             c::HANDLE_FLAG_INHERIT)
286                 })?;
287                 Ok(pipes.theirs.into_handle())
288             }
289
290             Stdio::Handle(ref handle) => {
291                 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
292             }
293
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).
297             Stdio::Null => {
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(),
302                     bInheritHandle: 1,
303                 };
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| {
309                     file.into_handle()
310                 })
311             }
312         }
313     }
314 }
315
316 impl From<AnonPipe> for Stdio {
317     fn from(pipe: AnonPipe) -> Stdio {
318         Stdio::Handle(pipe.into_handle())
319     }
320 }
321
322 impl From<File> for Stdio {
323     fn from(file: File) -> Stdio {
324         Stdio::Handle(file.into_handle())
325     }
326 }
327
328 ////////////////////////////////////////////////////////////////////////////////
329 // Processes
330 ////////////////////////////////////////////////////////////////////////////////
331
332 /// A value representing a child process.
333 ///
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.
337 pub struct Process {
338     handle: Handle,
339 }
340
341 impl Process {
342     pub fn kill(&mut self) -> io::Result<()> {
343         cvt(unsafe {
344             c::TerminateProcess(self.handle.raw(), 1)
345         })?;
346         Ok(())
347     }
348
349     pub fn id(&self) -> u32 {
350         unsafe {
351             c::GetProcessId(self.handle.raw()) as u32
352         }
353     }
354
355     pub fn wait(&mut self) -> io::Result<ExitStatus> {
356         unsafe {
357             let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
358             if res != c::WAIT_OBJECT_0 {
359                 return Err(Error::last_os_error())
360             }
361             let mut status = 0;
362             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
363             Ok(ExitStatus(status))
364         }
365     }
366
367     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
368         unsafe {
369             match c::WaitForSingleObject(self.handle.raw(), 0) {
370                 c::WAIT_OBJECT_0 => {}
371                 c::WAIT_TIMEOUT => {
372                     return Ok(None);
373                 }
374                 _ => return Err(io::Error::last_os_error()),
375             }
376             let mut status = 0;
377             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
378             Ok(Some(ExitStatus(status)))
379         }
380     }
381
382     pub fn handle(&self) -> &Handle { &self.handle }
383
384     pub fn into_handle(self) -> Handle { self.handle }
385 }
386
387 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
388 pub struct ExitStatus(c::DWORD);
389
390 impl ExitStatus {
391     pub fn success(&self) -> bool {
392         self.0 == 0
393     }
394     pub fn code(&self) -> Option<i32> {
395         Some(self.0 as i32)
396     }
397 }
398
399 impl From<c::DWORD> for ExitStatus {
400     fn from(u: c::DWORD) -> ExitStatus {
401         ExitStatus(u)
402     }
403 }
404
405 impl fmt::Display for ExitStatus {
406     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407         write!(f, "exit code: {}", self.0)
408     }
409 }
410
411 fn zeroed_startupinfo() -> c::STARTUPINFO {
412     c::STARTUPINFO {
413         cb: 0,
414         lpReserved: ptr::null_mut(),
415         lpDesktop: ptr::null_mut(),
416         lpTitle: ptr::null_mut(),
417         dwX: 0,
418         dwY: 0,
419         dwXSize: 0,
420         dwYSize: 0,
421         dwXCountChars: 0,
422         dwYCountCharts: 0,
423         dwFillAttribute: 0,
424         dwFlags: 0,
425         wShowWindow: 0,
426         cbReserved2: 0,
427         lpReserved2: ptr::null_mut(),
428         hStdInput: c::INVALID_HANDLE_VALUE,
429         hStdOutput: c::INVALID_HANDLE_VALUE,
430         hStdError: c::INVALID_HANDLE_VALUE,
431     }
432 }
433
434 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
435     c::PROCESS_INFORMATION {
436         hProcess: ptr::null_mut(),
437         hThread: ptr::null_mut(),
438         dwProcessId: 0,
439         dwThreadId: 0
440     }
441 }
442
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)?;
452     for arg in args {
453         cmd.push(' ' as u16);
454         append_arg(&mut cmd, arg, false)?;
455     }
456     return Ok(cmd);
457
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();
466         if quote {
467             cmd.push('"' as u16);
468         }
469
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 {
474                 backslashes += 1;
475             } else {
476                 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);
480                     }
481                 }
482                 backslashes = 0;
483             }
484             cmd.push(x);
485         }
486
487         if quote {
488             // Add n backslashes to total 2n before ending '"'.
489             for _ in 0..backslashes {
490                 cmd.push('\\' as u16);
491             }
492             cmd.push('"' as u16);
493         }
494         Ok(())
495     }
496 }
497
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
502     // \0 to terminate.
503     if let Some(env) = maybe_env {
504         let mut blk = Vec::new();
505
506         for (k, v) in env {
507             blk.extend(ensure_no_nuls(k.0)?.encode_wide());
508             blk.push('=' as u16);
509             blk.extend(ensure_no_nuls(v)?.encode_wide());
510             blk.push(0);
511         }
512         blk.push(0);
513         Ok((blk.as_mut_ptr() as *mut c_void, blk))
514     } else {
515         Ok((ptr::null_mut(), Vec::new()))
516     }
517 }
518
519 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
520
521     match d {
522         Some(dir) => {
523             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
524             dir_str.push(0);
525             Ok((dir_str.as_ptr(), dir_str))
526         },
527         None => Ok((ptr::null(), Vec::new()))
528     }
529 }
530
531 #[cfg(test)]
532 mod tests {
533     use ffi::{OsStr, OsString};
534     use super::make_command_line;
535
536     #[test]
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),
540                                                   &args.iter()
541                                                        .map(|a| OsString::from(a))
542                                                        .collect::<Vec<OsString>>())
543                                     .unwrap();
544             String::from_utf16(command_line).unwrap()
545         }
546
547         assert_eq!(
548             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
549             "\"prog\" aaa bbb ccc"
550         );
551
552         assert_eq!(
553             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
554             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
555         );
556         assert_eq!(
557             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
558             "\"C:\\Program Files\\test\" aa\\\"bb"
559         );
560         assert_eq!(
561             test_wrapper("echo", &["a b c"]),
562             "\"echo\" \"a b c\""
563         );
564         assert_eq!(
565             test_wrapper("echo", &["\" \\\" \\", "\\"]),
566             "\"echo\" \"\\\" \\\\\\\" \\\\\" \\"
567         );
568         assert_eq!(
569             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
570             "\"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}\""
571         );
572     }
573 }