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.
11 use libc::{pid_t, c_void, c_int};
19 use io::process::{ProcessExit, ExitStatus, ExitSignal};
21 use path::BytesContainer;
23 use io::{IoResult, IoError};
26 use sys::{mod, retry, c, wouldblock, set_nonblocking, ms_to_timeval, timer};
27 use sys::fs::FileDesc;
28 use sys_common::helper_thread::Helper;
29 use sys_common::{AsInner, mkerr_libc, timeout};
31 use io::fs::PathExtensions;
33 pub use sys_common::ProcessConfig;
35 /// A value representing a child process.
37 /// The lifetime of this value is linked to the lifetime of the actual
38 /// process - the Process destructor calls self.finish() which waits
39 /// for the process to terminate.
41 /// The unique id of the process (this should never be negative).
44 /// A HANDLE to the process, which will prevent the pid being
45 /// re-used until the handle is closed.
49 impl Drop for Process {
51 free_handle(self.handle);
56 pub fn id(&self) -> pid_t {
60 pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
61 Process::killpid(self.pid, signal)
64 pub unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
65 let handle = libc::OpenProcess(libc::PROCESS_TERMINATE |
66 libc::PROCESS_QUERY_INFORMATION,
67 libc::FALSE, pid as libc::DWORD);
69 return Err(super::last_error())
71 let ret = match signal {
72 // test for existence on signal 0
75 let ret = libc::GetExitCodeProcess(handle, &mut status);
77 Err(super::last_error())
78 } else if status != libc::STILL_ACTIVE {
80 kind: io::InvalidInput,
81 desc: "no process to kill",
88 15 | 9 => { // sigterm or sigkill
89 let ret = libc::TerminateProcess(handle, 1);
90 super::mkerr_winbool(ret)
93 kind: io::IoUnavailable,
94 desc: "unsupported signal on windows",
98 let _ = libc::CloseHandle(handle);
102 pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
103 out_fd: Option<P>, err_fd: Option<P>)
105 where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
106 K: BytesContainer + Eq + Hash, V: BytesContainer
108 use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
109 use libc::consts::os::extra::{
111 STARTF_USESTDHANDLES,
112 INVALID_HANDLE_VALUE,
113 DUPLICATE_SAME_ACCESS
115 use libc::funcs::extra::kernel32::{
121 use libc::funcs::extra::msvcrt::get_osfhandle;
124 use iter::{Iterator, IteratorExt};
127 if cfg.gid().is_some() || cfg.uid().is_some() {
129 kind: io::IoUnavailable,
130 desc: "unsupported gid/uid requested on windows",
135 // To have the spawning semantics of unix/windows stay the same, we need to
136 // read the *child's* PATH if one is provided. See #15149 for more details.
137 let program = cfg.env().and_then(|env| {
138 for (key, v) in env.iter() {
139 if b"PATH" != key.container_as_bytes() { continue }
141 // Split the value and test each path to see if the
143 for path in os::split_paths(v.container_as_bytes()).into_iter() {
144 let path = path.join(cfg.program().as_bytes_no_nul())
145 .with_extension(os::consts::EXE_EXTENSION);
147 return Some(path.to_c_str())
156 let mut si = zeroed_startupinfo();
157 si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
158 si.dwFlags = STARTF_USESTDHANDLES;
160 let cur_proc = GetCurrentProcess();
162 // Similarly to unix, we don't actually leave holes for the stdio file
163 // descriptors, but rather open up /dev/null equivalents. These
164 // equivalents are drawn from libuv's windows process spawning.
165 let set_fd = |fd: &Option<P>, slot: &mut HANDLE,
169 let access = if is_stdin {
170 libc::FILE_GENERIC_READ
172 libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
174 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
175 let mut sa = libc::SECURITY_ATTRIBUTES {
176 nLength: size as libc::DWORD,
177 lpSecurityDescriptor: ptr::null_mut(),
180 let mut filename: Vec<u16> = "NUL".utf16_units().collect();
182 *slot = libc::CreateFileW(filename.as_ptr(),
184 libc::FILE_SHARE_READ |
185 libc::FILE_SHARE_WRITE,
190 if *slot == INVALID_HANDLE_VALUE {
191 return Err(super::last_error())
195 let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
196 if orig == INVALID_HANDLE_VALUE {
197 return Err(super::last_error())
199 if DuplicateHandle(cur_proc, orig, cur_proc, slot,
200 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
201 return Err(super::last_error())
208 try!(set_fd(&in_fd, &mut si.hStdInput, true));
209 try!(set_fd(&out_fd, &mut si.hStdOutput, false));
210 try!(set_fd(&err_fd, &mut si.hStdError, false));
212 let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
214 let mut pi = zeroed_process_information();
215 let mut create_err = None;
217 // stolen from the libuv code.
218 let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
220 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
223 with_envp(cfg.env(), |envp| {
224 with_dirp(cfg.cwd(), |dirp| {
225 let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
227 let created = CreateProcessW(ptr::null(),
228 cmd_str.as_mut_ptr(),
234 if created == FALSE {
235 create_err = Some(super::last_error());
240 assert!(CloseHandle(si.hStdInput) != 0);
241 assert!(CloseHandle(si.hStdOutput) != 0);
242 assert!(CloseHandle(si.hStdError) != 0);
245 Some(err) => return Err(err),
249 // We close the thread handle because we don't care about keeping the
250 // thread id valid, and we aren't keeping the thread handle around to be
251 // able to close it later. We don't close the process handle however
252 // because std::we want the process id to stay valid at least until the
253 // calling code closes the process handle.
254 assert!(CloseHandle(pi.hThread) != 0);
257 pid: pi.dwProcessId as pid_t,
258 handle: pi.hProcess as *mut ()
263 /// Waits for a process to exit and returns the exit code, failing
264 /// if there is no process with the specified id.
266 /// Note that this is private to avoid race conditions on unix where if
267 /// a user calls waitpid(some_process.get_id()) then some_process.finish()
268 /// and some_process.destroy() and some_process.finalize() will then either
269 /// operate on a none-existent process or, even worse, on a newer process
270 /// with the same id.
271 pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> {
272 use libc::types::os::arch::extra::DWORD;
273 use libc::consts::os::extra::{
275 PROCESS_QUERY_INFORMATION,
282 use libc::funcs::extra::kernel32::{
290 let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
293 if process.is_null() {
294 return Err(super::last_error())
299 if GetExitCodeProcess(process, &mut status) == FALSE {
300 let err = Err(super::last_error());
301 assert!(CloseHandle(process) != 0);
304 if status != STILL_ACTIVE {
305 assert!(CloseHandle(process) != 0);
306 return Ok(ExitStatus(status as int));
308 let interval = if deadline == 0 {
311 let now = timer::now();
312 if deadline < now {0} else {(deadline - now) as u32}
314 match WaitForSingleObject(process, interval) {
317 assert!(CloseHandle(process) != 0);
318 return Err(timeout("process wait timed out"))
321 let err = Err(super::last_error());
322 assert!(CloseHandle(process) != 0);
331 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
332 libc::types::os::arch::extra::STARTUPINFO {
334 lpReserved: ptr::null_mut(),
335 lpDesktop: ptr::null_mut(),
336 lpTitle: ptr::null_mut(),
347 lpReserved2: ptr::null_mut(),
348 hStdInput: libc::INVALID_HANDLE_VALUE,
349 hStdOutput: libc::INVALID_HANDLE_VALUE,
350 hStdError: libc::INVALID_HANDLE_VALUE,
354 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
355 libc::types::os::arch::extra::PROCESS_INFORMATION {
356 hProcess: ptr::null_mut(),
357 hThread: ptr::null_mut(),
363 fn make_command_line(prog: &CString, args: &[CString]) -> String {
364 let mut cmd = String::new();
365 append_arg(&mut cmd, prog.as_str()
366 .expect("expected program name to be utf-8 encoded"));
367 for arg in args.iter() {
369 append_arg(&mut cmd, arg.as_str()
370 .expect("expected argument to be utf-8 encoded"));
374 fn append_arg(cmd: &mut String, arg: &str) {
375 // If an argument has 0 characters then we need to quote it to ensure
376 // that it actually gets passed through on the command line or otherwise
377 // it will be dropped entirely when parsed on the other end.
378 let quote = arg.chars().any(|c| c == ' ' || c == '\t') || arg.len() == 0;
382 let argvec: Vec<char> = arg.chars().collect();
383 for i in range(0u, argvec.len()) {
384 append_char_at(cmd, argvec.as_slice(), i);
391 fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
395 cmd.push_str("\\\"");
398 if backslash_run_ends_in_quote(arg, i) {
399 // Double all backslashes that are in runs before quotes.
400 cmd.push_str("\\\\");
402 // Pass other backslashes through unescaped.
412 fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
413 while i < s.len() && s[i] == '\\' {
416 return i < s.len() && s[i] == '"';
420 fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T where
421 K: BytesContainer + Eq + Hash, V: BytesContainer, F: FnOnce(*mut c_void) -> T,
423 // On Windows we pass an "environment block" which is not a char**, but
424 // rather a concatenation of null-terminated k=v\0 sequences, with a final
428 let mut blk = Vec::new();
430 for pair in env.iter() {
431 let kv = format!("{}={}",
432 pair.0.container_as_str().unwrap(),
433 pair.1.container_as_str().unwrap());
434 blk.extend(kv.utf16_units());
440 cb(blk.as_mut_ptr() as *mut c_void)
442 _ => cb(ptr::null_mut())
446 fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
447 F: FnOnce(*const u16) -> T,
451 let dir_str = dir.as_str()
452 .expect("expected workingdirectory to be utf-8 encoded");
453 let mut dir_str: Vec<u16> = dir_str.utf16_units().collect();
457 None => cb(ptr::null())
461 fn free_handle(handle: *mut ()) {
463 libc::CloseHandle(mem::transmute(handle)) != 0
471 fn test_make_command_line() {
475 use super::make_command_line;
477 fn test_wrapper(prog: &str, args: &[&str]) -> String {
478 make_command_line(&prog.to_c_str(),
480 .map(|a| a.to_c_str())
481 .collect::<Vec<CString>>()
486 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
491 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
492 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
495 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
496 "\"C:\\Program Files\\test\" aa\\\"bb"
499 test_wrapper("echo", &["a b c"]),
503 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
504 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"