]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
doc: fix a broken link
[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 wait(&self) -> io::Result<ExitStatus> {
197         use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0};
198         use libc::{GetExitCodeProcess, WaitForSingleObject};
199
200         unsafe {
201             loop {
202                 let mut status = 0;
203                 try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status)));
204                 if status != STILL_ACTIVE {
205                     return Ok(ExitStatus(status as i32));
206                 }
207                 match WaitForSingleObject(self.handle.raw(), INFINITE) {
208                     WAIT_OBJECT_0 => {}
209                     _ => return Err(Error::last_os_error()),
210                 }
211             }
212         }
213     }
214 }
215
216 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
217 pub struct ExitStatus(i32);
218
219 impl ExitStatus {
220     pub fn success(&self) -> bool {
221         self.0 == 0
222     }
223     pub fn code(&self) -> Option<i32> {
224         Some(self.0)
225     }
226 }
227
228 impl fmt::Display for ExitStatus {
229     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230         write!(f, "exit code: {}", self.0)
231     }
232 }
233
234 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
235     libc::types::os::arch::extra::STARTUPINFO {
236         cb: 0,
237         lpReserved: ptr::null_mut(),
238         lpDesktop: ptr::null_mut(),
239         lpTitle: ptr::null_mut(),
240         dwX: 0,
241         dwY: 0,
242         dwXSize: 0,
243         dwYSize: 0,
244         dwXCountChars: 0,
245         dwYCountCharts: 0,
246         dwFillAttribute: 0,
247         dwFlags: 0,
248         wShowWindow: 0,
249         cbReserved2: 0,
250         lpReserved2: ptr::null_mut(),
251         hStdInput: libc::INVALID_HANDLE_VALUE,
252         hStdOutput: libc::INVALID_HANDLE_VALUE,
253         hStdError: libc::INVALID_HANDLE_VALUE,
254     }
255 }
256
257 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
258     libc::types::os::arch::extra::PROCESS_INFORMATION {
259         hProcess: ptr::null_mut(),
260         hThread: ptr::null_mut(),
261         dwProcessId: 0,
262         dwThreadId: 0
263     }
264 }
265
266 // Produces a wide string *without terminating null*
267 fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> {
268     // Encode the command and arguments in a command line string such
269     // that the spawned process may recover them using CommandLineToArgvW.
270     let mut cmd: Vec<u16> = Vec::new();
271     append_arg(&mut cmd, prog);
272     for arg in args {
273         cmd.push(' ' as u16);
274         append_arg(&mut cmd, arg);
275     }
276     return cmd;
277
278     fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) {
279         // If an argument has 0 characters then we need to quote it to ensure
280         // that it actually gets passed through on the command line or otherwise
281         // it will be dropped entirely when parsed on the other end.
282         let arg_bytes = &arg.as_inner().inner.as_inner();
283         let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
284             || arg_bytes.is_empty();
285         if quote {
286             cmd.push('"' as u16);
287         }
288
289         let mut iter = arg.encode_wide();
290         let mut backslashes: usize = 0;
291         while let Some(x) = iter.next() {
292             if x == '\\' as u16 {
293                 backslashes += 1;
294             } else {
295                 if x == '"' as u16 {
296                     // Add n+1 backslashes to total 2n+1 before internal '"'.
297                     for _ in 0..(backslashes+1) {
298                         cmd.push('\\' as u16);
299                     }
300                 }
301                 backslashes = 0;
302             }
303             cmd.push(x);
304         }
305
306         if quote {
307             // Add n backslashes to total 2n before ending '"'.
308             for _ in 0..backslashes {
309                 cmd.push('\\' as u16);
310             }
311             cmd.push('"' as u16);
312         }
313     }
314 }
315
316 fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
317              -> (*mut c_void, Vec<u16>) {
318     // On Windows we pass an "environment block" which is not a char**, but
319     // rather a concatenation of null-terminated k=v\0 sequences, with a final
320     // \0 to terminate.
321     match env {
322         Some(env) => {
323             let mut blk = Vec::new();
324
325             for pair in env {
326                 blk.extend(pair.0.encode_wide());
327                 blk.push('=' as u16);
328                 blk.extend(pair.1.encode_wide());
329                 blk.push(0);
330             }
331             blk.push(0);
332             (blk.as_mut_ptr() as *mut c_void, blk)
333         }
334         _ => (ptr::null_mut(), Vec::new())
335     }
336 }
337
338 fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) {
339     match d {
340         Some(dir) => {
341             let mut dir_str: Vec<u16> = dir.encode_wide().collect();
342             dir_str.push(0);
343             (dir_str.as_ptr(), dir_str)
344         },
345         None => (ptr::null(), Vec::new())
346     }
347 }
348
349 impl Stdio {
350     fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> {
351         use libc::DUPLICATE_SAME_ACCESS;
352
353         match *self {
354             Stdio::Inherit => {
355                 stdio::get(stdio_id).and_then(|io| {
356                     io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
357                 })
358             }
359             Stdio::Piped(ref pipe) => {
360                 pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
361             }
362
363             // Similarly to unix, we don't actually leave holes for the
364             // stdio file descriptors, but rather open up /dev/null
365             // equivalents. These equivalents are drawn from libuv's
366             // windows process spawning.
367             Stdio::None => {
368                 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
369                 let mut sa = libc::SECURITY_ATTRIBUTES {
370                     nLength: size as libc::DWORD,
371                     lpSecurityDescriptor: ptr::null_mut(),
372                     bInheritHandle: 1,
373                 };
374                 let mut opts = OpenOptions::new();
375                 opts.read(stdio_id == c::STD_INPUT_HANDLE);
376                 opts.write(stdio_id != c::STD_INPUT_HANDLE);
377                 opts.security_attributes(&mut sa);
378                 File::open(Path::new("NUL"), &opts).map(|file| {
379                     file.into_handle()
380                 })
381             }
382         }
383     }
384 }
385
386 #[cfg(test)]
387 mod tests {
388     use prelude::v1::*;
389     use str;
390     use ffi::{OsStr, OsString};
391     use super::make_command_line;
392
393     #[test]
394     fn test_make_command_line() {
395         fn test_wrapper(prog: &str, args: &[&str]) -> String {
396             String::from_utf16(
397                 &make_command_line(OsStr::new(prog),
398                                    &args.iter()
399                                         .map(|a| OsString::from(a))
400                                         .collect::<Vec<OsString>>())).unwrap()
401         }
402
403         assert_eq!(
404             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
405             "prog aaa bbb ccc"
406         );
407
408         assert_eq!(
409             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
410             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
411         );
412         assert_eq!(
413             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
414             "\"C:\\Program Files\\test\" aa\\\"bb"
415         );
416         assert_eq!(
417             test_wrapper("echo", &["a b c"]),
418             "echo \"a b c\""
419         );
420         assert_eq!(
421             test_wrapper("echo", &["\" \\\" \\", "\\"]),
422             "echo \"\\\" \\\\\\\" \\\\\" \\"
423         );
424         assert_eq!(
425             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
426             "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
427         );
428     }
429 }