]>
Commit | Line | Data |
---|---|---|
85aaf69f SL |
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; | |
bd371182 | 16 | use env::split_paths; |
85aaf69f SL |
17 | use env; |
18 | use ffi::{OsString, OsStr}; | |
19 | use fmt; | |
c34b1796 | 20 | use fs; |
85aaf69f SL |
21 | use io::{self, Error}; |
22 | use libc::{self, c_void}; | |
bd371182 | 23 | use mem; |
c34b1796 | 24 | use os::windows::ffi::OsStrExt; |
bd371182 | 25 | use path::Path; |
85aaf69f SL |
26 | use ptr; |
27 | use sync::{StaticMutex, MUTEX_INIT}; | |
bd371182 AL |
28 | use sys::c; |
29 | use sys::fs2::{OpenOptions, File}; | |
c34b1796 | 30 | use sys::handle::Handle; |
85aaf69f | 31 | use sys::pipe2::AnonPipe; |
bd371182 | 32 | use sys::stdio; |
85aaf69f | 33 | use sys::{self, cvt}; |
85aaf69f SL |
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 | ||
85aaf69f SL |
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 { | |
85aaf69f SL |
105 | handle: Handle, |
106 | } | |
107 | ||
9346a6ac AL |
108 | pub enum Stdio { |
109 | Inherit, | |
110 | Piped(AnonPipe), | |
111 | None, | |
112 | } | |
113 | ||
85aaf69f | 114 | impl Process { |
85aaf69f | 115 | pub fn spawn(cfg: &Command, |
bd371182 AL |
116 | in_handle: Stdio, |
117 | out_handle: Stdio, | |
118 | err_handle: Stdio) -> io::Result<Process> | |
85aaf69f | 119 | { |
bd371182 AL |
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. | |
85aaf69f SL |
126 | let program = cfg.env.as_ref().and_then(|env| { |
127 | for (key, v) in env { | |
9346a6ac | 128 | if OsStr::new("PATH") != &**key { continue } |
85aaf69f SL |
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); | |
c34b1796 AL |
135 | if fs::metadata(&path).is_ok() { |
136 | return Some(path.into_os_string()) | |
85aaf69f SL |
137 | } |
138 | } | |
139 | break | |
140 | } | |
141 | None | |
142 | }); | |
143 | ||
bd371182 AL |
144 | let mut si = zeroed_startupinfo(); |
145 | si.cb = mem::size_of::<STARTUPINFO>() as DWORD; | |
146 | si.dwFlags = STARTF_USESTDHANDLES; | |
85aaf69f | 147 | |
bd371182 AL |
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)); | |
85aaf69f | 151 | |
bd371182 AL |
152 | si.hStdInput = stdin.raw(); |
153 | si.hStdOutput = stdout.raw(); | |
154 | si.hStdError = stderr.raw(); | |
85aaf69f | 155 | |
bd371182 AL |
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 | |
85aaf69f | 159 | |
bd371182 AL |
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 | } | |
85aaf69f | 165 | |
bd371182 AL |
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 | }); | |
85aaf69f | 182 | |
bd371182 AL |
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)); | |
85aaf69f | 187 | |
bd371182 | 188 | Ok(Process { handle: Handle::new(pi.hProcess) }) |
85aaf69f SL |
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> { | |
bd371182 AL |
197 | use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0}; |
198 | use libc::{GetExitCodeProcess, WaitForSingleObject}; | |
85aaf69f SL |
199 | |
200 | unsafe { | |
201 | loop { | |
202 | let mut status = 0; | |
bd371182 | 203 | try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status))); |
85aaf69f SL |
204 | if status != STILL_ACTIVE { |
205 | return Ok(ExitStatus(status as i32)); | |
206 | } | |
207 | match WaitForSingleObject(self.handle.raw(), INFINITE) { | |
208 | WAIT_OBJECT_0 => {} | |
bd371182 | 209 | _ => return Err(Error::last_os_error()), |
85aaf69f SL |
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 | let mut cmd: Vec<u16> = Vec::new(); | |
269 | append_arg(&mut cmd, prog); | |
270 | for arg in args { | |
271 | cmd.push(' ' as u16); | |
272 | append_arg(&mut cmd, arg); | |
273 | } | |
274 | return cmd; | |
275 | ||
276 | fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) { | |
277 | // If an argument has 0 characters then we need to quote it to ensure | |
278 | // that it actually gets passed through on the command line or otherwise | |
279 | // it will be dropped entirely when parsed on the other end. | |
280 | let arg_bytes = &arg.as_inner().inner.as_inner(); | |
281 | let quote = arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') | |
9346a6ac | 282 | || arg_bytes.is_empty(); |
85aaf69f SL |
283 | if quote { |
284 | cmd.push('"' as u16); | |
285 | } | |
286 | ||
287 | let mut iter = arg.encode_wide(); | |
288 | while let Some(x) = iter.next() { | |
289 | if x == '"' as u16 { | |
290 | // escape quotes | |
291 | cmd.push('\\' as u16); | |
292 | cmd.push('"' as u16); | |
293 | } else if x == '\\' as u16 { | |
294 | // is this a run of backslashes followed by a " ? | |
295 | if iter.clone().skip_while(|y| *y == '\\' as u16).next() == Some('"' as u16) { | |
296 | // Double it ... NOTE: this behavior is being | |
297 | // preserved as it's been part of Rust for a long | |
298 | // time, but no one seems to know exactly why this | |
299 | // is the right thing to do. | |
300 | cmd.push('\\' as u16); | |
301 | cmd.push('\\' as u16); | |
302 | } else { | |
303 | // Push it through unescaped | |
304 | cmd.push('\\' as u16); | |
305 | } | |
306 | } else { | |
307 | cmd.push(x) | |
308 | } | |
309 | } | |
310 | ||
311 | if quote { | |
312 | cmd.push('"' as u16); | |
313 | } | |
314 | } | |
315 | } | |
316 | ||
bd371182 AL |
317 | fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>) |
318 | -> (*mut c_void, Vec<u16>) { | |
85aaf69f SL |
319 | // On Windows we pass an "environment block" which is not a char**, but |
320 | // rather a concatenation of null-terminated k=v\0 sequences, with a final | |
321 | // \0 to terminate. | |
322 | match env { | |
323 | Some(env) => { | |
324 | let mut blk = Vec::new(); | |
325 | ||
326 | for pair in env { | |
327 | blk.extend(pair.0.encode_wide()); | |
328 | blk.push('=' as u16); | |
329 | blk.extend(pair.1.encode_wide()); | |
330 | blk.push(0); | |
331 | } | |
332 | blk.push(0); | |
bd371182 | 333 | (blk.as_mut_ptr() as *mut c_void, blk) |
85aaf69f | 334 | } |
bd371182 | 335 | _ => (ptr::null_mut(), Vec::new()) |
85aaf69f SL |
336 | } |
337 | } | |
338 | ||
bd371182 | 339 | fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) { |
85aaf69f | 340 | match d { |
bd371182 AL |
341 | Some(dir) => { |
342 | let mut dir_str: Vec<u16> = dir.encode_wide().collect(); | |
343 | dir_str.push(0); | |
344 | (dir_str.as_ptr(), dir_str) | |
345 | }, | |
346 | None => (ptr::null(), Vec::new()) | |
347 | } | |
348 | } | |
349 | ||
350 | impl Stdio { | |
351 | fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> { | |
352 | use libc::DUPLICATE_SAME_ACCESS; | |
353 | ||
354 | match *self { | |
355 | Stdio::Inherit => { | |
356 | stdio::get(stdio_id).and_then(|io| { | |
357 | io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS) | |
358 | }) | |
359 | } | |
360 | Stdio::Piped(ref pipe) => { | |
361 | pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS) | |
362 | } | |
363 | ||
364 | // Similarly to unix, we don't actually leave holes for the | |
365 | // stdio file descriptors, but rather open up /dev/null | |
366 | // equivalents. These equivalents are drawn from libuv's | |
367 | // windows process spawning. | |
368 | Stdio::None => { | |
369 | let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>(); | |
370 | let mut sa = libc::SECURITY_ATTRIBUTES { | |
371 | nLength: size as libc::DWORD, | |
372 | lpSecurityDescriptor: ptr::null_mut(), | |
373 | bInheritHandle: 1, | |
374 | }; | |
375 | let mut opts = OpenOptions::new(); | |
376 | opts.read(stdio_id == c::STD_INPUT_HANDLE); | |
377 | opts.write(stdio_id != c::STD_INPUT_HANDLE); | |
378 | opts.security_attributes(&mut sa); | |
379 | File::open(Path::new("NUL"), &opts).map(|file| { | |
380 | file.into_handle() | |
381 | }) | |
382 | } | |
383 | } | |
85aaf69f SL |
384 | } |
385 | } | |
386 | ||
387 | #[cfg(test)] | |
388 | mod tests { | |
389 | use prelude::v1::*; | |
390 | use str; | |
391 | use ffi::{OsStr, OsString}; | |
392 | use super::make_command_line; | |
393 | ||
394 | #[test] | |
395 | fn test_make_command_line() { | |
396 | fn test_wrapper(prog: &str, args: &[&str]) -> String { | |
397 | String::from_utf16( | |
9346a6ac | 398 | &make_command_line(OsStr::new(prog), |
c34b1796 AL |
399 | &args.iter() |
400 | .map(|a| OsString::from(a)) | |
401 | .collect::<Vec<OsString>>())).unwrap() | |
85aaf69f SL |
402 | } |
403 | ||
404 | assert_eq!( | |
405 | test_wrapper("prog", &["aaa", "bbb", "ccc"]), | |
406 | "prog aaa bbb ccc" | |
407 | ); | |
408 | ||
409 | assert_eq!( | |
410 | test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]), | |
411 | "\"C:\\Program Files\\blah\\blah.exe\" aaa" | |
412 | ); | |
413 | assert_eq!( | |
414 | test_wrapper("C:\\Program Files\\test", &["aa\"bb"]), | |
415 | "\"C:\\Program Files\\test\" aa\\\"bb" | |
416 | ); | |
417 | assert_eq!( | |
418 | test_wrapper("echo", &["a b c"]), | |
419 | "echo \"a b c\"" | |
420 | ); | |
421 | assert_eq!( | |
422 | test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]), | |
423 | "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}" | |
424 | ); | |
425 | } | |
426 | } |