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.
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.
13 use libc::{pid_t, c_void};
20 use io::process::{ProcessExit, ExitStatus};
22 use path::BytesContainer;
24 use io::{IoResult, IoError};
27 use sys::fs::FileDesc;
28 use sys_common::{AsInner, timeout};
30 use io::fs::PathExtensions;
32 pub use sys_common::ProcessConfig;
34 /// A value representing a child process.
36 /// The lifetime of this value is linked to the lifetime of the actual
37 /// process - the Process destructor calls self.finish() which waits
38 /// for the process to terminate.
40 /// The unique id of the process (this should never be negative).
43 /// A HANDLE to the process, which will prevent the pid being
44 /// re-used until the handle is closed.
48 impl Drop for Process {
50 free_handle(self.handle);
55 pub fn id(&self) -> pid_t {
59 pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
60 Process::killpid(self.pid, signal)
63 pub unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
64 let handle = libc::OpenProcess(libc::PROCESS_TERMINATE |
65 libc::PROCESS_QUERY_INFORMATION,
66 libc::FALSE, pid as libc::DWORD);
68 return Err(super::last_error())
70 let ret = match signal {
71 // test for existence on signal 0
74 let ret = libc::GetExitCodeProcess(handle, &mut status);
76 Err(super::last_error())
77 } else if status != libc::STILL_ACTIVE {
79 kind: io::InvalidInput,
80 desc: "no process to kill",
87 15 | 9 => { // sigterm or sigkill
88 let ret = libc::TerminateProcess(handle, 1);
89 super::mkerr_winbool(ret)
92 kind: io::IoUnavailable,
93 desc: "unsupported signal on windows",
97 let _ = libc::CloseHandle(handle);
101 pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
102 out_fd: Option<P>, err_fd: Option<P>)
104 where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
105 K: BytesContainer + Eq + Hash, V: BytesContainer
107 use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
108 use libc::consts::os::extra::{
110 STARTF_USESTDHANDLES,
111 INVALID_HANDLE_VALUE,
112 DUPLICATE_SAME_ACCESS
114 use libc::funcs::extra::kernel32::{
120 use libc::funcs::extra::msvcrt::get_osfhandle;
124 if cfg.gid().is_some() || cfg.uid().is_some() {
126 kind: io::IoUnavailable,
127 desc: "unsupported gid/uid requested on windows",
132 // To have the spawning semantics of unix/windows stay the same, we need to
133 // read the *child's* PATH if one is provided. See #15149 for more details.
134 let program = cfg.env().and_then(|env| {
135 for (key, v) in env.iter() {
136 if b"PATH" != key.container_as_bytes() { continue }
138 // Split the value and test each path to see if the
140 for path in os::split_paths(v.container_as_bytes()).into_iter() {
141 let path = path.join(cfg.program().as_bytes_no_nul())
142 .with_extension(os::consts::EXE_EXTENSION);
144 return Some(path.to_c_str())
153 let mut si = zeroed_startupinfo();
154 si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
155 si.dwFlags = STARTF_USESTDHANDLES;
157 let cur_proc = GetCurrentProcess();
159 // Similarly to unix, we don't actually leave holes for the stdio file
160 // descriptors, but rather open up /dev/null equivalents. These
161 // equivalents are drawn from libuv's windows process spawning.
162 let set_fd = |fd: &Option<P>, slot: &mut HANDLE,
166 let access = if is_stdin {
167 libc::FILE_GENERIC_READ
169 libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
171 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
172 let mut sa = libc::SECURITY_ATTRIBUTES {
173 nLength: size as libc::DWORD,
174 lpSecurityDescriptor: ptr::null_mut(),
177 let mut filename: Vec<u16> = "NUL".utf16_units().collect();
179 *slot = libc::CreateFileW(filename.as_ptr(),
181 libc::FILE_SHARE_READ |
182 libc::FILE_SHARE_WRITE,
187 if *slot == INVALID_HANDLE_VALUE {
188 return Err(super::last_error())
192 let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
193 if orig == INVALID_HANDLE_VALUE {
194 return Err(super::last_error())
196 if DuplicateHandle(cur_proc, orig, cur_proc, slot,
197 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
198 return Err(super::last_error())
205 try!(set_fd(&in_fd, &mut si.hStdInput, true));
206 try!(set_fd(&out_fd, &mut si.hStdOutput, false));
207 try!(set_fd(&err_fd, &mut si.hStdError, false));
209 let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
211 let mut pi = zeroed_process_information();
212 let mut create_err = None;
214 // stolen from the libuv code.
215 let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
217 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
220 with_envp(cfg.env(), |envp| {
221 with_dirp(cfg.cwd(), |dirp| {
222 let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
224 let created = CreateProcessW(ptr::null(),
225 cmd_str.as_mut_ptr(),
231 if created == FALSE {
232 create_err = Some(super::last_error());
237 assert!(CloseHandle(si.hStdInput) != 0);
238 assert!(CloseHandle(si.hStdOutput) != 0);
239 assert!(CloseHandle(si.hStdError) != 0);
242 Some(err) => return Err(err),
246 // We close the thread handle because we don't care about keeping the
247 // thread id valid, and we aren't keeping the thread handle around to be
248 // able to close it later. We don't close the process handle however
249 // because std::we want the process id to stay valid at least until the
250 // calling code closes the process handle.
251 assert!(CloseHandle(pi.hThread) != 0);
254 pid: pi.dwProcessId as pid_t,
255 handle: pi.hProcess as *mut ()
260 /// Waits for a process to exit and returns the exit code, failing
261 /// if there is no process with the specified id.
263 /// Note that this is private to avoid race conditions on unix where if
264 /// a user calls waitpid(some_process.get_id()) then some_process.finish()
265 /// and some_process.destroy() and some_process.finalize() will then either
266 /// operate on a none-existent process or, even worse, on a newer process
267 /// with the same id.
268 pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> {
269 use libc::types::os::arch::extra::DWORD;
270 use libc::consts::os::extra::{
272 PROCESS_QUERY_INFORMATION,
279 use libc::funcs::extra::kernel32::{
287 let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
290 if process.is_null() {
291 return Err(super::last_error())
296 if GetExitCodeProcess(process, &mut status) == FALSE {
297 let err = Err(super::last_error());
298 assert!(CloseHandle(process) != 0);
301 if status != STILL_ACTIVE {
302 assert!(CloseHandle(process) != 0);
303 return Ok(ExitStatus(status as int));
305 let interval = if deadline == 0 {
308 let now = timer::now();
309 if deadline < now {0} else {(deadline - now) as u32}
311 match WaitForSingleObject(process, interval) {
314 assert!(CloseHandle(process) != 0);
315 return Err(timeout("process wait timed out"))
318 let err = Err(super::last_error());
319 assert!(CloseHandle(process) != 0);
328 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
329 libc::types::os::arch::extra::STARTUPINFO {
331 lpReserved: ptr::null_mut(),
332 lpDesktop: ptr::null_mut(),
333 lpTitle: ptr::null_mut(),
344 lpReserved2: ptr::null_mut(),
345 hStdInput: libc::INVALID_HANDLE_VALUE,
346 hStdOutput: libc::INVALID_HANDLE_VALUE,
347 hStdError: libc::INVALID_HANDLE_VALUE,
351 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
352 libc::types::os::arch::extra::PROCESS_INFORMATION {
353 hProcess: ptr::null_mut(),
354 hThread: ptr::null_mut(),
360 fn make_command_line(prog: &CString, args: &[CString]) -> String {
361 let mut cmd = String::new();
362 append_arg(&mut cmd, prog.as_str()
363 .expect("expected program name to be utf-8 encoded"));
364 for arg in args.iter() {
366 append_arg(&mut cmd, arg.as_str()
367 .expect("expected argument to be utf-8 encoded"));
371 fn append_arg(cmd: &mut String, arg: &str) {
372 // If an argument has 0 characters then we need to quote it to ensure
373 // that it actually gets passed through on the command line or otherwise
374 // it will be dropped entirely when parsed on the other end.
375 let quote = arg.chars().any(|c| c == ' ' || c == '\t') || arg.len() == 0;
379 let argvec: Vec<char> = arg.chars().collect();
380 for i in range(0u, argvec.len()) {
381 append_char_at(cmd, argvec.as_slice(), i);
388 fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
392 cmd.push_str("\\\"");
395 if backslash_run_ends_in_quote(arg, i) {
396 // Double all backslashes that are in runs before quotes.
397 cmd.push_str("\\\\");
399 // Pass other backslashes through unescaped.
409 fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
410 while i < s.len() && s[i] == '\\' {
413 return i < s.len() && s[i] == '"';
417 fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T where
418 K: BytesContainer + Eq + Hash, V: BytesContainer, F: FnOnce(*mut c_void) -> T,
420 // On Windows we pass an "environment block" which is not a char**, but
421 // rather a concatenation of null-terminated k=v\0 sequences, with a final
425 let mut blk = Vec::new();
427 for pair in env.iter() {
428 let kv = format!("{}={}",
429 pair.0.container_as_str().unwrap(),
430 pair.1.container_as_str().unwrap());
431 blk.extend(kv.utf16_units());
437 cb(blk.as_mut_ptr() as *mut c_void)
439 _ => cb(ptr::null_mut())
443 fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
444 F: FnOnce(*const u16) -> T,
448 let dir_str = dir.as_str()
449 .expect("expected workingdirectory to be utf-8 encoded");
450 let mut dir_str: Vec<u16> = dir_str.utf16_units().collect();
454 None => cb(ptr::null())
458 fn free_handle(handle: *mut ()) {
460 libc::CloseHandle(mem::transmute(handle)) != 0
468 fn test_make_command_line() {
472 use super::make_command_line;
474 fn test_wrapper(prog: &str, args: &[&str]) -> String {
475 make_command_line(&prog.to_c_str(),
477 .map(|a| a.to_c_str())
478 .collect::<Vec<CString>>()
483 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
488 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
489 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
492 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
493 "\"C:\\Program Files\\test\" aa\\\"bb"
496 test_wrapper("echo", &["a b c"]),
500 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
501 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"