]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
Rollup merge of #33867 - oli-obk:rustdoc_variant_types, r=GuillaumeGomez
[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 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 sys::mutex::Mutex;
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 struct DropGuard<'a> {
79     lock: &'a Mutex,
80 }
81
82 impl Command {
83     pub fn new(program: &OsStr) -> Command {
84         Command {
85             program: program.to_os_string(),
86             args: Vec::new(),
87             env: None,
88             cwd: None,
89             detach: false,
90             stdin: None,
91             stdout: None,
92             stderr: None,
93         }
94     }
95
96     pub fn arg(&mut self, arg: &OsStr) {
97         self.args.push(arg.to_os_string())
98     }
99     fn init_env_map(&mut self){
100         if self.env.is_none() {
101             self.env = Some(env::vars_os().map(|(key, val)| {
102                 (mk_key(&key), val)
103             }).collect());
104         }
105     }
106     pub fn env(&mut self, key: &OsStr, val: &OsStr) {
107         self.init_env_map();
108         self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
109     }
110     pub fn env_remove(&mut self, key: &OsStr) {
111         self.init_env_map();
112         self.env.as_mut().unwrap().remove(&mk_key(key));
113     }
114     pub fn env_clear(&mut self) {
115         self.env = Some(HashMap::new())
116     }
117     pub fn cwd(&mut self, dir: &OsStr) {
118         self.cwd = Some(dir.to_os_string())
119     }
120     pub fn stdin(&mut self, stdin: Stdio) {
121         self.stdin = Some(stdin);
122     }
123     pub fn stdout(&mut self, stdout: Stdio) {
124         self.stdout = Some(stdout);
125     }
126     pub fn stderr(&mut self, stderr: Stdio) {
127         self.stderr = Some(stderr);
128     }
129
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
134         // details.
135         let program = self.env.as_ref().and_then(|env| {
136             for (key, v) in env {
137                 if OsStr::new("PATH") != &**key { continue }
138
139                 // Split the value and test each path to see if the
140                 // program exists.
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())
146                     }
147                 }
148                 break
149             }
150             None
151         });
152
153         let mut si = zeroed_startupinfo();
154         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
155         si.dwFlags = c::STARTF_USESTDHANDLES;
156
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
160
161         // stolen from the libuv code.
162         let mut flags = c::CREATE_UNICODE_ENVIRONMENT;
163         if self.detach {
164             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
165         }
166
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();
170
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.
177         //
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);
182
183         let mut pipes = StdioPipes {
184             stdin: None,
185             stdout: None,
186             stderr: None,
187         };
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,
195                                       &mut pipes.stdout)?;
196         let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
197                                       &mut pipes.stderr)?;
198         si.hStdInput = stdin.raw();
199         si.hStdOutput = stdout.raw();
200         si.hStdError = stderr.raw();
201
202         unsafe {
203             cvt(c::CreateProcessW(ptr::null(),
204                                   cmd_str.as_mut_ptr(),
205                                   ptr::null_mut(),
206                                   ptr::null_mut(),
207                                   c::TRUE, flags, envp, dirp,
208                                   &mut si, &mut pi))
209         }?;
210
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));
215
216         Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
217     }
218
219 }
220
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)?;
226         }
227         Ok(())
228     }
229 }
230
231 impl<'a> DropGuard<'a> {
232     fn new(lock: &'a Mutex) -> DropGuard<'a> {
233         unsafe {
234             lock.lock();
235             DropGuard { lock: lock }
236         }
237     }
238 }
239
240 impl<'a> Drop for DropGuard<'a> {
241     fn drop(&mut self) {
242         unsafe {
243             self.lock.unlock();
244         }
245     }
246 }
247
248 impl Stdio {
249     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
250                  -> io::Result<Handle> {
251         match *self {
252             // If no stdio handle is available, then inherit means that it
253             // should still be unavailable so propagate the
254             // INVALID_HANDLE_VALUE.
255             Stdio::Inherit => {
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)),
260                 }
261             }
262
263             Stdio::MakePipe => {
264                 let (reader, writer) = pipe::anon_pipe()?;
265                 let (ours, theirs) = if stdio_id == c::STD_INPUT_HANDLE {
266                     (writer, reader)
267                 } else {
268                     (reader, writer)
269                 };
270                 *pipe = Some(ours);
271                 cvt(unsafe {
272                     c::SetHandleInformation(theirs.handle().raw(),
273                                             c::HANDLE_FLAG_INHERIT,
274                                             c::HANDLE_FLAG_INHERIT)
275                 })?;
276                 Ok(theirs.into_handle())
277             }
278
279             Stdio::Handle(ref handle) => {
280                 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
281             }
282
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).
286             Stdio::Null => {
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(),
291                     bInheritHandle: 1,
292                 };
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| {
298                     file.into_handle()
299                 })
300             }
301         }
302     }
303 }
304
305 ////////////////////////////////////////////////////////////////////////////////
306 // Processes
307 ////////////////////////////////////////////////////////////////////////////////
308
309 /// A value representing a child process.
310 ///
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.
314 pub struct Process {
315     handle: Handle,
316 }
317
318 impl Process {
319     pub fn kill(&mut self) -> io::Result<()> {
320         cvt(unsafe {
321             c::TerminateProcess(self.handle.raw(), 1)
322         })?;
323         Ok(())
324     }
325
326     pub fn id(&self) -> u32 {
327         unsafe {
328             c::GetProcessId(self.handle.raw()) as u32
329         }
330     }
331
332     pub fn wait(&mut self) -> io::Result<ExitStatus> {
333         unsafe {
334             let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
335             if res != c::WAIT_OBJECT_0 {
336                 return Err(Error::last_os_error())
337             }
338             let mut status = 0;
339             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
340             Ok(ExitStatus(status))
341         }
342     }
343
344     pub fn handle(&self) -> &Handle { &self.handle }
345
346     pub fn into_handle(self) -> Handle { self.handle }
347 }
348
349 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
350 pub struct ExitStatus(c::DWORD);
351
352 impl ExitStatus {
353     pub fn success(&self) -> bool {
354         self.0 == 0
355     }
356     pub fn code(&self) -> Option<i32> {
357         Some(self.0 as i32)
358     }
359 }
360
361 impl From<c::DWORD> for ExitStatus {
362     fn from(u: c::DWORD) -> ExitStatus {
363         ExitStatus(u)
364     }
365 }
366
367 impl fmt::Display for ExitStatus {
368     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369         write!(f, "exit code: {}", self.0)
370     }
371 }
372
373 fn zeroed_startupinfo() -> c::STARTUPINFO {
374     c::STARTUPINFO {
375         cb: 0,
376         lpReserved: ptr::null_mut(),
377         lpDesktop: ptr::null_mut(),
378         lpTitle: ptr::null_mut(),
379         dwX: 0,
380         dwY: 0,
381         dwXSize: 0,
382         dwYSize: 0,
383         dwXCountChars: 0,
384         dwYCountCharts: 0,
385         dwFillAttribute: 0,
386         dwFlags: 0,
387         wShowWindow: 0,
388         cbReserved2: 0,
389         lpReserved2: ptr::null_mut(),
390         hStdInput: c::INVALID_HANDLE_VALUE,
391         hStdOutput: c::INVALID_HANDLE_VALUE,
392         hStdError: c::INVALID_HANDLE_VALUE,
393     }
394 }
395
396 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
397     c::PROCESS_INFORMATION {
398         hProcess: ptr::null_mut(),
399         hThread: ptr::null_mut(),
400         dwProcessId: 0,
401         dwThreadId: 0
402     }
403 }
404
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)?;
412     for arg in args {
413         cmd.push(' ' as u16);
414         append_arg(&mut cmd, arg)?;
415     }
416     return Ok(cmd);
417
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();
426         if quote {
427             cmd.push('"' as u16);
428         }
429
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 {
434                 backslashes += 1;
435             } else {
436                 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);
440                     }
441                 }
442                 backslashes = 0;
443             }
444             cmd.push(x);
445         }
446
447         if quote {
448             // Add n backslashes to total 2n before ending '"'.
449             for _ in 0..backslashes {
450                 cmd.push('\\' as u16);
451             }
452             cmd.push('"' as u16);
453         }
454         Ok(())
455     }
456 }
457
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
462     // \0 to terminate.
463     match env {
464         Some(env) => {
465             let mut blk = Vec::new();
466
467             for pair in env {
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());
471                 blk.push(0);
472             }
473             blk.push(0);
474             Ok((blk.as_mut_ptr() as *mut c_void, blk))
475         }
476         _ => Ok((ptr::null_mut(), Vec::new()))
477     }
478 }
479
480 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
481
482     match d {
483         Some(dir) => {
484             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
485             dir_str.push(0);
486             Ok((dir_str.as_ptr(), dir_str))
487         },
488         None => Ok((ptr::null(), Vec::new()))
489     }
490 }
491
492 #[cfg(test)]
493 mod tests {
494     use prelude::v1::*;
495     use ffi::{OsStr, OsString};
496     use super::make_command_line;
497
498     #[test]
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),
502                                                   &args.iter()
503                                                        .map(|a| OsString::from(a))
504                                                        .collect::<Vec<OsString>>())
505                                     .unwrap();
506             String::from_utf16(command_line).unwrap()
507         }
508
509         assert_eq!(
510             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
511             "prog aaa bbb ccc"
512         );
513
514         assert_eq!(
515             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
516             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
517         );
518         assert_eq!(
519             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
520             "\"C:\\Program Files\\test\" aa\\\"bb"
521         );
522         assert_eq!(
523             test_wrapper("echo", &["a b c"]),
524             "echo \"a b c\""
525         );
526         assert_eq!(
527             test_wrapper("echo", &["\" \\\" \\", "\\"]),
528             "echo \"\\\" \\\\\\\" \\\\\" \\"
529         );
530         assert_eq!(
531             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
532             "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
533         );
534     }
535 }