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