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, c_int};
15 use c_str::{CString, ToCStr};
20 use io::process::{ProcessExit, ExitStatus, ExitSignal};
22 use path::BytesContainer;
24 use io::{IoResult, IoError};
27 use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval, timer};
28 use sys::fs::FileDesc;
29 use sys_common::helper_thread::Helper;
30 use sys_common::{AsInner, mkerr_libc, timeout};
32 use io::fs::PathExtensions;
34 pub use sys_common::ProcessConfig;
36 /// A value representing a child process.
38 /// The lifetime of this value is linked to the lifetime of the actual
39 /// process - the Process destructor calls self.finish() which waits
40 /// for the process to terminate.
42 /// The unique id of the process (this should never be negative).
45 /// A HANDLE to the process, which will prevent the pid being
46 /// re-used until the handle is closed.
50 impl Drop for Process {
52 free_handle(self.handle);
57 pub fn id(&self) -> pid_t {
61 pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
62 Process::killpid(self.pid, signal)
65 pub unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
66 let handle = libc::OpenProcess(libc::PROCESS_TERMINATE |
67 libc::PROCESS_QUERY_INFORMATION,
68 libc::FALSE, pid as libc::DWORD);
70 return Err(super::last_error())
72 let ret = match signal {
73 // test for existence on signal 0
76 let ret = libc::GetExitCodeProcess(handle, &mut status);
78 Err(super::last_error())
79 } else if status != libc::STILL_ACTIVE {
81 kind: io::InvalidInput,
82 desc: "no process to kill",
89 15 | 9 => { // sigterm or sigkill
90 let ret = libc::TerminateProcess(handle, 1);
91 super::mkerr_winbool(ret)
94 kind: io::IoUnavailable,
95 desc: "unsupported signal on windows",
99 let _ = libc::CloseHandle(handle);
103 pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
104 out_fd: Option<P>, err_fd: Option<P>)
106 where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
107 K: BytesContainer + Eq + Hash, V: BytesContainer
109 use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
110 use libc::consts::os::extra::{
112 STARTF_USESTDHANDLES,
113 INVALID_HANDLE_VALUE,
114 DUPLICATE_SAME_ACCESS
116 use libc::funcs::extra::kernel32::{
122 use libc::funcs::extra::msvcrt::get_osfhandle;
125 use iter::{Iterator, IteratorExt};
128 if cfg.gid().is_some() || cfg.uid().is_some() {
130 kind: io::IoUnavailable,
131 desc: "unsupported gid/uid requested on windows",
136 // To have the spawning semantics of unix/windows stay the same, we need to
137 // read the *child's* PATH if one is provided. See #15149 for more details.
138 let program = cfg.env().and_then(|env| {
139 for (key, v) in env.iter() {
140 if b"PATH" != key.container_as_bytes() { continue }
142 // Split the value and test each path to see if the
144 for path in os::split_paths(v.container_as_bytes()).into_iter() {
145 let path = path.join(cfg.program().as_bytes_no_nul())
146 .with_extension(os::consts::EXE_EXTENSION);
148 return Some(path.to_c_str())
157 let mut si = zeroed_startupinfo();
158 si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
159 si.dwFlags = STARTF_USESTDHANDLES;
161 let cur_proc = GetCurrentProcess();
163 // Similarly to unix, we don't actually leave holes for the stdio file
164 // descriptors, but rather open up /dev/null equivalents. These
165 // equivalents are drawn from libuv's windows process spawning.
166 let set_fd = |&: fd: &Option<P>, slot: &mut HANDLE,
170 let access = if is_stdin {
171 libc::FILE_GENERIC_READ
173 libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
175 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
176 let mut sa = libc::SECURITY_ATTRIBUTES {
177 nLength: size as libc::DWORD,
178 lpSecurityDescriptor: ptr::null_mut(),
181 let mut filename: Vec<u16> = "NUL".utf16_units().collect();
183 *slot = libc::CreateFileW(filename.as_ptr(),
185 libc::FILE_SHARE_READ |
186 libc::FILE_SHARE_WRITE,
191 if *slot == INVALID_HANDLE_VALUE {
192 return Err(super::last_error())
196 let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
197 if orig == INVALID_HANDLE_VALUE {
198 return Err(super::last_error())
200 if DuplicateHandle(cur_proc, orig, cur_proc, slot,
201 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
202 return Err(super::last_error())
209 try!(set_fd(&in_fd, &mut si.hStdInput, true));
210 try!(set_fd(&out_fd, &mut si.hStdOutput, false));
211 try!(set_fd(&err_fd, &mut si.hStdError, false));
213 let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
215 let mut pi = zeroed_process_information();
216 let mut create_err = None;
218 // stolen from the libuv code.
219 let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
221 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
224 with_envp(cfg.env(), |envp| {
225 with_dirp(cfg.cwd(), |dirp| {
226 let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
228 let created = CreateProcessW(ptr::null(),
229 cmd_str.as_mut_ptr(),
235 if created == FALSE {
236 create_err = Some(super::last_error());
241 assert!(CloseHandle(si.hStdInput) != 0);
242 assert!(CloseHandle(si.hStdOutput) != 0);
243 assert!(CloseHandle(si.hStdError) != 0);
246 Some(err) => return Err(err),
250 // We close the thread handle because we don't care about keeping the
251 // thread id valid, and we aren't keeping the thread handle around to be
252 // able to close it later. We don't close the process handle however
253 // because std::we want the process id to stay valid at least until the
254 // calling code closes the process handle.
255 assert!(CloseHandle(pi.hThread) != 0);
258 pid: pi.dwProcessId as pid_t,
259 handle: pi.hProcess as *mut ()
264 /// Waits for a process to exit and returns the exit code, failing
265 /// if there is no process with the specified id.
267 /// Note that this is private to avoid race conditions on unix where if
268 /// a user calls waitpid(some_process.get_id()) then some_process.finish()
269 /// and some_process.destroy() and some_process.finalize() will then either
270 /// operate on a none-existent process or, even worse, on a newer process
271 /// with the same id.
272 pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> {
273 use libc::types::os::arch::extra::DWORD;
274 use libc::consts::os::extra::{
276 PROCESS_QUERY_INFORMATION,
283 use libc::funcs::extra::kernel32::{
291 let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
294 if process.is_null() {
295 return Err(super::last_error())
300 if GetExitCodeProcess(process, &mut status) == FALSE {
301 let err = Err(super::last_error());
302 assert!(CloseHandle(process) != 0);
305 if status != STILL_ACTIVE {
306 assert!(CloseHandle(process) != 0);
307 return Ok(ExitStatus(status as int));
309 let interval = if deadline == 0 {
312 let now = timer::now();
313 if deadline < now {0} else {(deadline - now) as u32}
315 match WaitForSingleObject(process, interval) {
318 assert!(CloseHandle(process) != 0);
319 return Err(timeout("process wait timed out"))
322 let err = Err(super::last_error());
323 assert!(CloseHandle(process) != 0);
332 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
333 libc::types::os::arch::extra::STARTUPINFO {
335 lpReserved: ptr::null_mut(),
336 lpDesktop: ptr::null_mut(),
337 lpTitle: ptr::null_mut(),
348 lpReserved2: ptr::null_mut(),
349 hStdInput: libc::INVALID_HANDLE_VALUE,
350 hStdOutput: libc::INVALID_HANDLE_VALUE,
351 hStdError: libc::INVALID_HANDLE_VALUE,
355 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
356 libc::types::os::arch::extra::PROCESS_INFORMATION {
357 hProcess: ptr::null_mut(),
358 hThread: ptr::null_mut(),
364 fn make_command_line(prog: &CString, args: &[CString]) -> String {
365 let mut cmd = String::new();
366 append_arg(&mut cmd, prog.as_str()
367 .expect("expected program name to be utf-8 encoded"));
368 for arg in args.iter() {
370 append_arg(&mut cmd, arg.as_str()
371 .expect("expected argument to be utf-8 encoded"));
375 fn append_arg(cmd: &mut String, arg: &str) {
376 // If an argument has 0 characters then we need to quote it to ensure
377 // that it actually gets passed through on the command line or otherwise
378 // it will be dropped entirely when parsed on the other end.
379 let quote = arg.chars().any(|c| c == ' ' || c == '\t') || arg.len() == 0;
383 let argvec: Vec<char> = arg.chars().collect();
384 for i in range(0u, argvec.len()) {
385 append_char_at(cmd, argvec.as_slice(), i);
392 fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
396 cmd.push_str("\\\"");
399 if backslash_run_ends_in_quote(arg, i) {
400 // Double all backslashes that are in runs before quotes.
401 cmd.push_str("\\\\");
403 // Pass other backslashes through unescaped.
413 fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
414 while i < s.len() && s[i] == '\\' {
417 return i < s.len() && s[i] == '"';
421 fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T where
422 K: BytesContainer + Eq + Hash, V: BytesContainer, F: FnOnce(*mut c_void) -> T,
424 // On Windows we pass an "environment block" which is not a char**, but
425 // rather a concatenation of null-terminated k=v\0 sequences, with a final
429 let mut blk = Vec::new();
431 for pair in env.iter() {
432 let kv = format!("{}={}",
433 pair.0.container_as_str().unwrap(),
434 pair.1.container_as_str().unwrap());
435 blk.extend(kv.utf16_units());
441 cb(blk.as_mut_ptr() as *mut c_void)
443 _ => cb(ptr::null_mut())
447 fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
448 F: FnOnce(*const u16) -> T,
452 let dir_str = dir.as_str()
453 .expect("expected workingdirectory to be utf-8 encoded");
454 let mut dir_str: Vec<u16> = dir_str.utf16_units().collect();
458 None => cb(ptr::null())
462 fn free_handle(handle: *mut ()) {
464 libc::CloseHandle(mem::transmute(handle)) != 0
473 fn test_make_command_line() {
477 use super::make_command_line;
479 fn test_wrapper(prog: &str, args: &[&str]) -> String {
480 make_command_line(&prog.to_c_str(),
482 .map(|a| a.to_c_str())
483 .collect::<Vec<CString>>()
488 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
493 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
494 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
497 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
498 "\"C:\\Program Files\\test\" aa\\\"bb"
501 test_wrapper("echo", &["a b c"]),
505 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
506 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"