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 #[cfg(stage0)] use collections::hash_map::Hasher;
18 use libc
::{pid_t, c_void}
;
21 use old_io
::fs
::PathExtensions
;
22 use old_io
::process
::{ProcessExit, ExitStatus}
;
23 use old_io
::{IoResult, IoError}
;
26 use old_path
::BytesContainer
;
29 use sync
::{StaticMutex, MUTEX_INIT}
;
30 use sys
::fs
::FileDesc
;
33 use sys_common
::{AsInner, timeout}
;
35 pub use sys_common
::ProcessConfig
;
37 // `CreateProcess` is racy!
38 // http://support.microsoft.com/kb/315939
39 static CREATE_PROCESS_LOCK
: StaticMutex
= MUTEX_INIT
;
41 /// A value representing a child process.
43 /// The lifetime of this value is linked to the lifetime of the actual
44 /// process - the Process destructor calls self.finish() which waits
45 /// for the process to terminate.
47 /// The unique id of the process (this should never be negative).
50 /// A HANDLE to the process, which will prevent the pid being
51 /// re-used until the handle is closed.
55 impl Drop
for Process
{
57 free_handle(self.handle
);
62 pub fn id(&self) -> pid_t
{
66 pub unsafe fn kill(&self, signal
: int
) -> IoResult
<()> {
67 Process
::killpid(self.pid
, signal
)
70 pub unsafe fn killpid(pid
: pid_t
, signal
: int
) -> IoResult
<()> {
71 let handle
= libc
::OpenProcess(libc
::PROCESS_TERMINATE
|
72 libc
::PROCESS_QUERY_INFORMATION
,
73 libc
::FALSE
, pid
as libc
::DWORD
);
75 return Err(super::last_error())
77 let ret
= match signal
{
78 // test for existence on signal 0
81 let ret
= libc
::GetExitCodeProcess(handle
, &mut status
);
83 Err(super::last_error())
84 } else if status
!= libc
::STILL_ACTIVE
{
86 kind
: old_io
::InvalidInput
,
87 desc
: "no process to kill",
94 15 | 9 => { // sigterm or sigkill
95 let ret
= libc
::TerminateProcess(handle
, 1);
96 super::mkerr_winbool(ret
)
99 kind
: old_io
::IoUnavailable
,
100 desc
: "unsupported signal on windows",
104 let _
= libc
::CloseHandle(handle
);
110 pub fn spawn
<K
, V
, C
, P
>(cfg
: &C
, in_fd
: Option
<P
>,
111 out_fd
: Option
<P
>, err_fd
: Option
<P
>)
113 where C
: ProcessConfig
<K
, V
>, P
: AsInner
<FileDesc
>,
114 K
: BytesContainer
+ Eq
+ Hash
<Hasher
>, V
: BytesContainer
116 use libc
::types
::os
::arch
::extra
::{DWORD, HANDLE, STARTUPINFO}
;
117 use libc
::consts
::os
::extra
::{
119 STARTF_USESTDHANDLES
,
120 INVALID_HANDLE_VALUE
,
121 DUPLICATE_SAME_ACCESS
123 use libc
::funcs
::extra
::kernel32
::{
129 use libc
::funcs
::extra
::msvcrt
::get_osfhandle
;
132 use iter
::IteratorExt
;
135 if cfg
.gid().is_some() || cfg
.uid().is_some() {
137 kind
: old_io
::IoUnavailable
,
138 desc
: "unsupported gid/uid requested on windows",
143 // To have the spawning semantics of unix/windows stay the same, we need to
144 // read the *child's* PATH if one is provided. See #15149 for more details.
145 let program
= cfg
.env().and_then(|env
| {
146 for (key
, v
) in env
{
147 if b
"PATH" != key
.container_as_bytes() { continue }
149 // Split the value and test each path to see if the
151 for path
in os
::split_paths(v
.container_as_bytes()) {
152 let path
= path
.join(cfg
.program().as_bytes())
153 .with_extension(env
::consts
::EXE_EXTENSION
);
155 return Some(CString
::from_slice(path
.as_vec()))
164 let mut si
= zeroed_startupinfo();
165 si
.cb
= mem
::size_of
::<STARTUPINFO
>() as DWORD
;
166 si
.dwFlags
= STARTF_USESTDHANDLES
;
168 let cur_proc
= GetCurrentProcess();
170 // Similarly to unix, we don't actually leave holes for the stdio file
171 // descriptors, but rather open up /dev/null equivalents. These
172 // equivalents are drawn from libuv's windows process spawning.
173 let set_fd
= |fd
: &Option
<P
>, slot
: &mut HANDLE
,
177 let access
= if is_stdin
{
178 libc
::FILE_GENERIC_READ
180 libc
::FILE_GENERIC_WRITE
| libc
::FILE_READ_ATTRIBUTES
182 let size
= mem
::size_of
::<libc
::SECURITY_ATTRIBUTES
>();
183 let mut sa
= libc
::SECURITY_ATTRIBUTES
{
184 nLength
: size
as libc
::DWORD
,
185 lpSecurityDescriptor
: ptr
::null_mut(),
188 let mut filename
: Vec
<u16> = "NUL".utf16_units().collect();
190 *slot
= libc
::CreateFileW(filename
.as_ptr(),
192 libc
::FILE_SHARE_READ
|
193 libc
::FILE_SHARE_WRITE
,
198 if *slot
== INVALID_HANDLE_VALUE
{
199 return Err(super::last_error())
203 let orig
= get_osfhandle(fd
.as_inner().fd()) as HANDLE
;
204 if orig
== INVALID_HANDLE_VALUE
{
205 return Err(super::last_error())
207 if DuplicateHandle(cur_proc
, orig
, cur_proc
, slot
,
208 0, TRUE
, DUPLICATE_SAME_ACCESS
) == FALSE
{
209 return Err(super::last_error())
216 try
!(set_fd(&in_fd
, &mut si
.hStdInput
, true));
217 try
!(set_fd(&out_fd
, &mut si
.hStdOutput
, false));
218 try
!(set_fd(&err_fd
, &mut si
.hStdError
, false));
220 let cmd_str
= make_command_line(program
.as_ref().unwrap_or(cfg
.program()),
222 let mut pi
= zeroed_process_information();
223 let mut create_err
= None
;
225 // stolen from the libuv code.
226 let mut flags
= libc
::CREATE_UNICODE_ENVIRONMENT
;
228 flags
|= libc
::DETACHED_PROCESS
| libc
::CREATE_NEW_PROCESS_GROUP
;
231 with_envp(cfg
.env(), |envp
| {
232 with_dirp(cfg
.cwd(), |dirp
| {
233 let mut cmd_str
: Vec
<u16> = cmd_str
.utf16_units().collect();
235 let _lock
= CREATE_PROCESS_LOCK
.lock().unwrap();
236 let created
= CreateProcessW(ptr
::null(),
237 cmd_str
.as_mut_ptr(),
243 if created
== FALSE
{
244 create_err
= Some(super::last_error());
249 assert
!(CloseHandle(si
.hStdInput
) != 0);
250 assert
!(CloseHandle(si
.hStdOutput
) != 0);
251 assert
!(CloseHandle(si
.hStdError
) != 0);
254 Some(err
) => return Err(err
),
258 // We close the thread handle because we don't care about keeping the
259 // thread id valid, and we aren't keeping the thread handle around to be
260 // able to close it later. We don't close the process handle however
261 // because std::we want the process id to stay valid at least until the
262 // calling code closes the process handle.
263 assert
!(CloseHandle(pi
.hThread
) != 0);
266 pid
: pi
.dwProcessId
as pid_t
,
267 handle
: pi
.hProcess
as *mut ()
273 pub fn spawn
<K
, V
, C
, P
>(cfg
: &C
, in_fd
: Option
<P
>,
274 out_fd
: Option
<P
>, err_fd
: Option
<P
>)
276 where C
: ProcessConfig
<K
, V
>, P
: AsInner
<FileDesc
>,
277 K
: BytesContainer
+ Eq
+ Hash
, V
: BytesContainer
279 use libc
::types
::os
::arch
::extra
::{DWORD, HANDLE, STARTUPINFO}
;
280 use libc
::consts
::os
::extra
::{
282 STARTF_USESTDHANDLES
,
283 INVALID_HANDLE_VALUE
,
284 DUPLICATE_SAME_ACCESS
286 use libc
::funcs
::extra
::kernel32
::{
292 use libc
::funcs
::extra
::msvcrt
::get_osfhandle
;
295 use iter
::IteratorExt
;
298 if cfg
.gid().is_some() || cfg
.uid().is_some() {
300 kind
: old_io
::IoUnavailable
,
301 desc
: "unsupported gid/uid requested on windows",
306 // To have the spawning semantics of unix/windows stay the same, we need to
307 // read the *child's* PATH if one is provided. See #15149 for more details.
308 let program
= cfg
.env().and_then(|env
| {
309 for (key
, v
) in env
{
310 if b
"PATH" != key
.container_as_bytes() { continue }
312 // Split the value and test each path to see if the
314 for path
in os
::split_paths(v
.container_as_bytes()) {
315 let path
= path
.join(cfg
.program().as_bytes())
316 .with_extension(env
::consts
::EXE_EXTENSION
);
318 return Some(CString
::from_slice(path
.as_vec()))
327 let mut si
= zeroed_startupinfo();
328 si
.cb
= mem
::size_of
::<STARTUPINFO
>() as DWORD
;
329 si
.dwFlags
= STARTF_USESTDHANDLES
;
331 let cur_proc
= GetCurrentProcess();
333 // Similarly to unix, we don't actually leave holes for the stdio file
334 // descriptors, but rather open up /dev/null equivalents. These
335 // equivalents are drawn from libuv's windows process spawning.
336 let set_fd
= |fd
: &Option
<P
>, slot
: &mut HANDLE
,
340 let access
= if is_stdin
{
341 libc
::FILE_GENERIC_READ
343 libc
::FILE_GENERIC_WRITE
| libc
::FILE_READ_ATTRIBUTES
345 let size
= mem
::size_of
::<libc
::SECURITY_ATTRIBUTES
>();
346 let mut sa
= libc
::SECURITY_ATTRIBUTES
{
347 nLength
: size
as libc
::DWORD
,
348 lpSecurityDescriptor
: ptr
::null_mut(),
351 let mut filename
: Vec
<u16> = "NUL".utf16_units().collect();
353 *slot
= libc
::CreateFileW(filename
.as_ptr(),
355 libc
::FILE_SHARE_READ
|
356 libc
::FILE_SHARE_WRITE
,
361 if *slot
== INVALID_HANDLE_VALUE
{
362 return Err(super::last_error())
366 let orig
= get_osfhandle(fd
.as_inner().fd()) as HANDLE
;
367 if orig
== INVALID_HANDLE_VALUE
{
368 return Err(super::last_error())
370 if DuplicateHandle(cur_proc
, orig
, cur_proc
, slot
,
371 0, TRUE
, DUPLICATE_SAME_ACCESS
) == FALSE
{
372 return Err(super::last_error())
379 try
!(set_fd(&in_fd
, &mut si
.hStdInput
, true));
380 try
!(set_fd(&out_fd
, &mut si
.hStdOutput
, false));
381 try
!(set_fd(&err_fd
, &mut si
.hStdError
, false));
383 let cmd_str
= make_command_line(program
.as_ref().unwrap_or(cfg
.program()),
385 let mut pi
= zeroed_process_information();
386 let mut create_err
= None
;
388 // stolen from the libuv code.
389 let mut flags
= libc
::CREATE_UNICODE_ENVIRONMENT
;
391 flags
|= libc
::DETACHED_PROCESS
| libc
::CREATE_NEW_PROCESS_GROUP
;
394 with_envp(cfg
.env(), |envp
| {
395 with_dirp(cfg
.cwd(), |dirp
| {
396 let mut cmd_str
: Vec
<u16> = cmd_str
.utf16_units().collect();
398 let _lock
= CREATE_PROCESS_LOCK
.lock().unwrap();
399 let created
= CreateProcessW(ptr
::null(),
400 cmd_str
.as_mut_ptr(),
406 if created
== FALSE
{
407 create_err
= Some(super::last_error());
412 assert
!(CloseHandle(si
.hStdInput
) != 0);
413 assert
!(CloseHandle(si
.hStdOutput
) != 0);
414 assert
!(CloseHandle(si
.hStdError
) != 0);
417 Some(err
) => return Err(err
),
421 // We close the thread handle because we don't care about keeping the
422 // thread id valid, and we aren't keeping the thread handle around to be
423 // able to close it later. We don't close the process handle however
424 // because std::we want the process id to stay valid at least until the
425 // calling code closes the process handle.
426 assert
!(CloseHandle(pi
.hThread
) != 0);
429 pid
: pi
.dwProcessId
as pid_t
,
430 handle
: pi
.hProcess
as *mut ()
435 /// Waits for a process to exit and returns the exit code, failing
436 /// if there is no process with the specified id.
438 /// Note that this is private to avoid race conditions on unix where if
439 /// a user calls waitpid(some_process.get_id()) then some_process.finish()
440 /// and some_process.destroy() and some_process.finalize() will then either
441 /// operate on a none-existent process or, even worse, on a newer process
442 /// with the same id.
443 pub fn wait(&self, deadline
: u64) -> IoResult
<ProcessExit
> {
444 use libc
::types
::os
::arch
::extra
::DWORD
;
445 use libc
::consts
::os
::extra
::{
447 PROCESS_QUERY_INFORMATION
,
454 use libc
::funcs
::extra
::kernel32
::{
462 let process
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
465 if process
.is_null() {
466 return Err(super::last_error())
471 if GetExitCodeProcess(process
, &mut status
) == FALSE
{
472 let err
= Err(super::last_error());
473 assert
!(CloseHandle(process
) != 0);
476 if status
!= STILL_ACTIVE
{
477 assert
!(CloseHandle(process
) != 0);
478 return Ok(ExitStatus(status
as int
));
480 let interval
= if deadline
== 0 {
483 let now
= timer
::now();
484 if deadline
< now {0}
else {(deadline - now) as u32}
486 match WaitForSingleObject(process
, interval
) {
489 assert
!(CloseHandle(process
) != 0);
490 return Err(timeout("process wait timed out"))
493 let err
= Err(super::last_error());
494 assert
!(CloseHandle(process
) != 0);
503 fn zeroed_startupinfo() -> libc
::types
::os
::arch
::extra
::STARTUPINFO
{
504 libc
::types
::os
::arch
::extra
::STARTUPINFO
{
506 lpReserved
: ptr
::null_mut(),
507 lpDesktop
: ptr
::null_mut(),
508 lpTitle
: ptr
::null_mut(),
519 lpReserved2
: ptr
::null_mut(),
520 hStdInput
: libc
::INVALID_HANDLE_VALUE
,
521 hStdOutput
: libc
::INVALID_HANDLE_VALUE
,
522 hStdError
: libc
::INVALID_HANDLE_VALUE
,
526 fn zeroed_process_information() -> libc
::types
::os
::arch
::extra
::PROCESS_INFORMATION
{
527 libc
::types
::os
::arch
::extra
::PROCESS_INFORMATION
{
528 hProcess
: ptr
::null_mut(),
529 hThread
: ptr
::null_mut(),
535 fn make_command_line(prog
: &CString
, args
: &[CString
]) -> String
{
536 let mut cmd
= String
::new();
537 append_arg(&mut cmd
, str::from_utf8(prog
.as_bytes()).ok()
538 .expect("expected program name to be utf-8 encoded"));
541 append_arg(&mut cmd
, str::from_utf8(arg
.as_bytes()).ok()
542 .expect("expected argument to be utf-8 encoded"));
546 fn append_arg(cmd
: &mut String
, arg
: &str) {
547 // If an argument has 0 characters then we need to quote it to ensure
548 // that it actually gets passed through on the command line or otherwise
549 // it will be dropped entirely when parsed on the other end.
550 let quote
= arg
.chars().any(|c
| c
== ' '
|| c
== '
\t'
) || arg
.len() == 0;
554 let argvec: Vec<char> = arg.chars().collect();
555 for i in 0..argvec.len() {
556 append_char_at(cmd, &argvec, i);
563 fn append_char_at(cmd
: &mut String
, arg
: &[char], i
: uint
) {
567 cmd.push_str("\\\"");
570 if backslash_run_ends_in_quote(arg, i) {
571 // Double all backslashes that are in runs before quotes.
572 cmd.push_str("\\\\");
574 // Pass other backslashes through unescaped.
584 fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
585 while i < s.len() && s[i] == '\\' {
588 return i < s.len() && s[i] == '"'
;
593 fn with_envp
<K
, V
, T
, F
>(env
: Option
<&collections
::HashMap
<K
, V
>>, cb
: F
) -> T
594 where K
: BytesContainer
+ Eq
+ Hash
<Hasher
>,
596 F
: FnOnce(*mut c_void
) -> T
,
598 // On Windows we pass an "environment block" which is not a char**, but
599 // rather a concatenation of null-terminated k=v\0 sequences, with a final
603 let mut blk
= Vec
::new();
606 let kv
= format
!("{}={}",
607 pair
.0.container_as_str().unwrap(),
608 pair
.1.container_as_str().unwrap());
609 blk
.extend(kv
.utf16_units());
615 cb(blk
.as_mut_ptr() as *mut c_void
)
617 _
=> cb(ptr
::null_mut())
621 fn with_envp
<K
, V
, T
, F
>(env
: Option
<&collections
::HashMap
<K
, V
>>, cb
: F
) -> T
622 where K
: BytesContainer
+ Eq
+ Hash
,
624 F
: FnOnce(*mut c_void
) -> T
,
626 // On Windows we pass an "environment block" which is not a char**, but
627 // rather a concatenation of null-terminated k=v\0 sequences, with a final
631 let mut blk
= Vec
::new();
634 let kv
= format
!("{}={}",
635 pair
.0.container_as_str().unwrap(),
636 pair
.1.container_as_str().unwrap());
637 blk
.extend(kv
.utf16_units());
643 cb(blk
.as_mut_ptr() as *mut c_void
)
645 _
=> cb(ptr
::null_mut())
649 fn with_dirp
<T
, F
>(d
: Option
<&CString
>, cb
: F
) -> T
where
650 F
: FnOnce(*const u16) -> T
,
654 let dir_str
= str::from_utf8(dir
.as_bytes()).ok()
655 .expect("expected workingdirectory to be utf-8 encoded");
656 let mut dir_str
: Vec
<u16> = dir_str
.utf16_units().collect();
660 None
=> cb(ptr
::null())
664 fn free_handle(handle
: *mut ()) {
666 libc
::CloseHandle(mem
::transmute(handle
)) != 0
675 use super::make_command_line
;
678 fn test_make_command_line() {
679 fn test_wrapper(prog
: &str, args
: &[&str]) -> String
{
680 make_command_line(&CString
::from_slice(prog
.as_bytes()),
682 .map(|a
| CString
::from_slice(a
.as_bytes()))
683 .collect
::<Vec
<CString
>>())
687 test_wrapper("prog", &["aaa", "bbb", "ccc"]),
692 test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
693 "\"C:\\Program Files\\blah\\blah.exe\" aaa"
696 test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
697 "\"C:\\Program Files\\test\" aa\\\"bb"
700 test_wrapper("echo", &["a b c"]),
704 test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
705 "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"