]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
Rollup merge of #25614 - parir:patch-2, 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 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};
22 use libc::{self, c_void};
23 use mem;
24 use os::windows::ffi::OsStrExt;
25 use path::Path;
26 use ptr;
27 use sync::{StaticMutex, MUTEX_INIT};
28 use sys::c;
29 use sys::fs::{OpenOptions, File};
30 use sys::handle::Handle;
31 use sys::pipe::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 #[derive(Clone)]
47 pub struct Command {
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
53 }
54
55 impl Command {
56     pub fn new(program: &OsStr) -> Command {
57         Command {
58             program: program.to_os_string(),
59             args: Vec::new(),
60             env: None,
61             cwd: None,
62             detach: false,
63         }
64     }
65
66     pub fn arg(&mut self, arg: &OsStr) {
67         self.args.push(arg.to_os_string())
68     }
69     pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
70         self.args.extend(args.map(OsStr::to_os_string))
71     }
72     fn init_env_map(&mut self){
73         if self.env.is_none() {
74             self.env = Some(env::vars_os().map(|(key, val)| {
75                 (mk_key(&key), val)
76             }).collect());
77         }
78     }
79     pub fn env(&mut self, key: &OsStr, val: &OsStr) {
80         self.init_env_map();
81         self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
82     }
83     pub fn env_remove(&mut self, key: &OsStr) {
84         self.init_env_map();
85         self.env.as_mut().unwrap().remove(&mk_key(key));
86     }
87     pub fn env_clear(&mut self) {
88         self.env = Some(HashMap::new())
89     }
90     pub fn cwd(&mut self, dir: &OsStr) {
91         self.cwd = Some(dir.to_os_string())
92     }
93 }
94
95 ////////////////////////////////////////////////////////////////////////////////
96 // Processes
97 ////////////////////////////////////////////////////////////////////////////////
98
99 /// A value representing a child process.
100 ///
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.
104 pub struct Process {
105     handle: Handle,
106 }
107
108 pub enum Stdio {
109     Inherit,
110     Piped(AnonPipe),
111     None,
112 }
113
114 impl Process {
115     pub fn spawn(cfg: &Command,
116                  in_handle: Stdio,
117                  out_handle: Stdio,
118                  err_handle: Stdio) -> io::Result<Process>
119     {
120         use libc::{TRUE, STARTF_USESTDHANDLES};
121         use libc::{DWORD, STARTUPINFO, CreateProcessW};
122
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
125         // details.
126         let program = cfg.env.as_ref().and_then(|env| {
127             for (key, v) in env {
128                 if OsStr::new("PATH") != &**key { continue }
129
130                 // Split the value and test each path to see if the
131                 // program exists.
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())
137                     }
138                 }
139                 break
140             }
141             None
142         });
143
144         let mut si = zeroed_startupinfo();
145         si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
146         si.dwFlags = STARTF_USESTDHANDLES;
147
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));
151
152         si.hStdInput = stdin.raw();
153         si.hStdOutput = stdout.raw();
154         si.hStdError = stderr.raw();
155
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
159
160         // stolen from the libuv code.
161         let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
162         if cfg.detach {
163             flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
164         }
165
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();
169         try!(unsafe {
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();
174
175             cvt(CreateProcessW(ptr::null(),
176                                cmd_str.as_mut_ptr(),
177                                ptr::null_mut(),
178                                ptr::null_mut(),
179                                TRUE, flags, envp, dirp,
180                                &mut si, &mut pi))
181         });
182
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));
187
188         Ok(Process { handle: Handle::new(pi.hProcess) })
189     }
190
191     pub unsafe fn kill(&self) -> io::Result<()> {
192         try!(cvt(libc::TerminateProcess(self.handle.raw(), 1)));
193         Ok(())
194     }
195
196     pub fn id(&self) -> u32 {
197         unsafe {
198             c::GetProcessId(self.handle.raw()) as u32
199         }
200     }
201
202     pub fn wait(&self) -> io::Result<ExitStatus> {
203         use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0};
204         use libc::{GetExitCodeProcess, WaitForSingleObject};
205
206         unsafe {
207             loop {
208                 let mut status = 0;
209                 try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status)));
210                 if status != STILL_ACTIVE {
211                     return Ok(ExitStatus(status as i32));
212                 }
213                 match WaitForSingleObject(self.handle.raw(), INFINITE) {
214                     WAIT_OBJECT_0 => {}
215                     _ => return Err(Error::last_os_error()),
216                 }
217             }
218         }
219     }
220 }
221
222 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
223 pub struct ExitStatus(i32);
224
225 impl ExitStatus {
226     pub fn success(&self) -> bool {
227         self.0 == 0
228     }
229     pub fn code(&self) -> Option<i32> {
230         Some(self.0)
231     }
232 }
233
234 impl fmt::Display for ExitStatus {
235     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
236         write!(f, "exit code: {}", self.0)
237     }
238 }
239
240 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
241     libc::types::os::arch::extra::STARTUPINFO {
242         cb: 0,
243         lpReserved: ptr::null_mut(),
244         lpDesktop: ptr::null_mut(),
245         lpTitle: ptr::null_mut(),
246         dwX: 0,
247         dwY: 0,
248         dwXSize: 0,
249         dwYSize: 0,
250         dwXCountChars: 0,
251         dwYCountCharts: 0,
252         dwFillAttribute: 0,
253         dwFlags: 0,
254         wShowWindow: 0,
255         cbReserved2: 0,
256         lpReserved2: ptr::null_mut(),
257         hStdInput: libc::INVALID_HANDLE_VALUE,
258         hStdOutput: libc::INVALID_HANDLE_VALUE,
259         hStdError: libc::INVALID_HANDLE_VALUE,
260     }
261 }
262
263 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
264     libc::types::os::arch::extra::PROCESS_INFORMATION {
265         hProcess: ptr::null_mut(),
266         hThread: ptr::null_mut(),
267         dwProcessId: 0,
268         dwThreadId: 0
269     }
270 }
271
272 // Produces a wide string *without terminating null*
273 fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> {
274     // Encode the command and arguments in a command line string such
275     // that the spawned process may recover them using CommandLineToArgvW.
276     let mut cmd: Vec<u16> = Vec::new();
277     append_arg(&mut cmd, prog);
278     for arg in args {
279         cmd.push(' ' as u16);
280         append_arg(&mut cmd, arg);
281     }
282     return cmd;
283
284     fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) {
285         // If an argument has 0 characters then we need to quote it to ensure
286         // that it actually gets passed through on the command line or otherwise
287         // it will be dropped entirely when parsed on the other end.
288         let arg_bytes = &arg.as_inner().inner.as_inner();
289         let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
290             || arg_bytes.is_empty();
291         if quote {
292             cmd.push('"' as u16);
293         }
294
295         let mut iter = arg.encode_wide();
296         let mut backslashes: usize = 0;
297         while let Some(x) = iter.next() {
298             if x == '\\' as u16 {
299                 backslashes += 1;
300             } else {
301                 if x == '"' as u16 {
302                     // Add n+1 backslashes to total 2n+1 before internal '"'.
303                     for _ in 0..(backslashes+1) {
304                         cmd.push('\\' as u16);
305                     }
306                 }
307                 backslashes = 0;
308             }
309             cmd.push(x);
310         }
311
312         if quote {
313             // Add n backslashes to total 2n before ending '"'.
314             for _ in 0..backslashes {
315                 cmd.push('\\' as u16);
316             }
317             cmd.push('"' as u16);
318         }
319     }
320 }
321
322 fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
323              -> (*mut c_void, Vec<u16>) {
324     // On Windows we pass an "environment block" which is not a char**, but
325     // rather a concatenation of null-terminated k=v\0 sequences, with a final
326     // \0 to terminate.
327     match env {
328         Some(env) => {
329             let mut blk = Vec::new();
330
331             for pair in env {
332                 blk.extend(pair.0.encode_wide());
333                 blk.push('=' as u16);
334                 blk.extend(pair.1.encode_wide());
335                 blk.push(0);
336             }
337             blk.push(0);
338             (blk.as_mut_ptr() as *mut c_void, blk)
339         }
340         _ => (ptr::null_mut(), Vec::new())
341     }
342 }
343
344 fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) {
345     match d {
346         Some(dir) => {
347             let mut dir_str: Vec<u16> = dir.encode_wide().collect();
348             dir_str.push(0);
349             (dir_str.as_ptr(), dir_str)
350         },
351         None => (ptr::null(), Vec::new())
352     }
353 }
354
355 impl Stdio {
356     fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> {
357         use libc::DUPLICATE_SAME_ACCESS;
358
359         match *self {
360             Stdio::Inherit => {
361                 stdio::get(stdio_id).and_then(|io| {
362                     io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
363                 })
364             }
365             Stdio::Piped(ref pipe) => {
366                 pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
367             }
368
369             // Similarly to unix, we don't actually leave holes for the
370             // stdio file descriptors, but rather open up /dev/null
371             // equivalents. These equivalents are drawn from libuv's
372             // windows process spawning.
373             Stdio::None => {
374                 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
375                 let mut sa = libc::SECURITY_ATTRIBUTES {
376                     nLength: size as libc::DWORD,
377                     lpSecurityDescriptor: ptr::null_mut(),
378                     bInheritHandle: 1,
379                 };
380                 let mut opts = OpenOptions::new();
381                 opts.read(stdio_id == c::STD_INPUT_HANDLE);
382                 opts.write(stdio_id != c::STD_INPUT_HANDLE);
383                 opts.security_attributes(&mut sa);
384                 File::open(Path::new("NUL"), &opts).map(|file| {
385                     file.into_handle()
386                 })
387             }
388         }
389     }
390 }
391
392 #[cfg(test)]
393 mod tests {
394     use prelude::v1::*;
395     use str;
396     use ffi::{OsStr, OsString};
397     use super::make_command_line;
398
399     #[test]
400     fn test_make_command_line() {
401         fn test_wrapper(prog: &str, args: &[&str]) -> String {
402             String::from_utf16(
403                 &make_command_line(OsStr::new(prog),
404                                    &args.iter()
405                                         .map(|a| OsString::from(a))
406                                         .collect::<Vec<OsString>>())).unwrap()
407         }
408
409         assert_eq!(
410             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
411             "prog aaa bbb ccc"
412         );
413
414         assert_eq!(
415             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
416             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
417         );
418         assert_eq!(
419             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
420             "\"C:\\Program Files\\test\" aa\\\"bb"
421         );
422         assert_eq!(
423             test_wrapper("echo", &["a b c"]),
424             "echo \"a b c\""
425         );
426         assert_eq!(
427             test_wrapper("echo", &["\" \\\" \\", "\\"]),
428             "echo \"\\\" \\\\\\\" \\\\\" \\"
429         );
430         assert_eq!(
431             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
432             "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
433         );
434     }
435 }