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