]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
doc: remove incomplete sentence
[rust.git] / src / libstd / sys / windows / process.rs
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 libc::{pid_t, c_void, c_int};
14 use libc;
15 use c_str::{CString, ToCStr};
16 use io;
17 use mem;
18 use os;
19 use ptr;
20 use io::process::{ProcessExit, ExitStatus, ExitSignal};
21 use collections;
22 use path::BytesContainer;
23 use hash::Hash;
24 use io::{IoResult, IoError};
25
26 use sys::fs;
27 use sys::{mod, 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};
31
32 use io::fs::PathExtensions;
33
34 pub use sys_common::ProcessConfig;
35
36 /// A value representing a child process.
37 ///
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.
41 pub struct Process {
42     /// The unique id of the process (this should never be negative).
43     pid: pid_t,
44
45     /// A HANDLE to the process, which will prevent the pid being
46     /// re-used until the handle is closed.
47     handle: *mut (),
48 }
49
50 impl Drop for Process {
51     fn drop(&mut self) {
52         free_handle(self.handle);
53     }
54 }
55
56 impl Process {
57     pub fn id(&self) -> pid_t {
58         self.pid
59     }
60
61     pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
62         Process::killpid(self.pid, signal)
63     }
64
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);
69         if handle.is_null() {
70             return Err(super::last_error())
71         }
72         let ret = match signal {
73             // test for existence on signal 0
74             0 => {
75                 let mut status = 0;
76                 let ret = libc::GetExitCodeProcess(handle, &mut status);
77                 if ret == 0 {
78                     Err(super::last_error())
79                 } else if status != libc::STILL_ACTIVE {
80                     Err(IoError {
81                         kind: io::InvalidInput,
82                         desc: "no process to kill",
83                         detail: None,
84                     })
85                 } else {
86                     Ok(())
87                 }
88             }
89             15 | 9 => { // sigterm or sigkill
90                 let ret = libc::TerminateProcess(handle, 1);
91                 super::mkerr_winbool(ret)
92             }
93             _ => Err(IoError {
94                 kind: io::IoUnavailable,
95                 desc: "unsupported signal on windows",
96                 detail: None,
97             })
98         };
99         let _ = libc::CloseHandle(handle);
100         return ret;
101     }
102
103     pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
104                               out_fd: Option<P>, err_fd: Option<P>)
105                               -> IoResult<Process>
106         where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
107               K: BytesContainer + Eq + Hash, V: BytesContainer
108     {
109         use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
110         use libc::consts::os::extra::{
111             TRUE, FALSE,
112             STARTF_USESTDHANDLES,
113             INVALID_HANDLE_VALUE,
114             DUPLICATE_SAME_ACCESS
115         };
116         use libc::funcs::extra::kernel32::{
117             GetCurrentProcess,
118             DuplicateHandle,
119             CloseHandle,
120             CreateProcessW
121         };
122         use libc::funcs::extra::msvcrt::get_osfhandle;
123
124         use mem;
125         use iter::{Iterator, IteratorExt};
126         use str::StrExt;
127
128         if cfg.gid().is_some() || cfg.uid().is_some() {
129             return Err(IoError {
130                 kind: io::IoUnavailable,
131                 desc: "unsupported gid/uid requested on windows",
132                 detail: None,
133             })
134         }
135
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 }
141
142                 // Split the value and test each path to see if the
143                 // program exists.
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);
147                     if path.exists() {
148                         return Some(path.to_c_str())
149                     }
150                 }
151                 break
152             }
153             None
154         });
155
156         unsafe {
157             let mut si = zeroed_startupinfo();
158             si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
159             si.dwFlags = STARTF_USESTDHANDLES;
160
161             let cur_proc = GetCurrentProcess();
162
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,
167                           is_stdin: bool| {
168                 match *fd {
169                     None => {
170                         let access = if is_stdin {
171                             libc::FILE_GENERIC_READ
172                         } else {
173                             libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
174                         };
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(),
179                             bInheritHandle: 1,
180                         };
181                         let mut filename: Vec<u16> = "NUL".utf16_units().collect();
182                         filename.push(0);
183                         *slot = libc::CreateFileW(filename.as_ptr(),
184                                                   access,
185                                                   libc::FILE_SHARE_READ |
186                                                       libc::FILE_SHARE_WRITE,
187                                                   &mut sa,
188                                                   libc::OPEN_EXISTING,
189                                                   0,
190                                                   ptr::null_mut());
191                         if *slot == INVALID_HANDLE_VALUE {
192                             return Err(super::last_error())
193                         }
194                     }
195                     Some(ref fd) => {
196                         let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
197                         if orig == INVALID_HANDLE_VALUE {
198                             return Err(super::last_error())
199                         }
200                         if DuplicateHandle(cur_proc, orig, cur_proc, slot,
201                                            0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
202                             return Err(super::last_error())
203                         }
204                     }
205                 }
206                 Ok(())
207             };
208
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));
212
213             let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
214                                             cfg.args());
215             let mut pi = zeroed_process_information();
216             let mut create_err = None;
217
218             // stolen from the libuv code.
219             let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
220             if cfg.detach() {
221                 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
222             }
223
224             with_envp(cfg.env(), |envp| {
225                 with_dirp(cfg.cwd(), |dirp| {
226                     let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
227                     cmd_str.push(0);
228                     let created = CreateProcessW(ptr::null(),
229                                                  cmd_str.as_mut_ptr(),
230                                                  ptr::null_mut(),
231                                                  ptr::null_mut(),
232                                                  TRUE,
233                                                  flags, envp, dirp,
234                                                  &mut si, &mut pi);
235                     if created == FALSE {
236                         create_err = Some(super::last_error());
237                     }
238                 })
239             });
240
241             assert!(CloseHandle(si.hStdInput) != 0);
242             assert!(CloseHandle(si.hStdOutput) != 0);
243             assert!(CloseHandle(si.hStdError) != 0);
244
245             match create_err {
246                 Some(err) => return Err(err),
247                 None => {}
248             }
249
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);
256
257             Ok(Process {
258                 pid: pi.dwProcessId as pid_t,
259                 handle: pi.hProcess as *mut ()
260             })
261         }
262     }
263
264     /// Waits for a process to exit and returns the exit code, failing
265     /// if there is no process with the specified id.
266     ///
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::{
275             SYNCHRONIZE,
276             PROCESS_QUERY_INFORMATION,
277             FALSE,
278             STILL_ACTIVE,
279             INFINITE,
280             WAIT_TIMEOUT,
281             WAIT_OBJECT_0,
282         };
283         use libc::funcs::extra::kernel32::{
284             OpenProcess,
285             GetExitCodeProcess,
286             CloseHandle,
287             WaitForSingleObject,
288         };
289
290         unsafe {
291             let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
292                                       FALSE,
293                                       self.pid as DWORD);
294             if process.is_null() {
295                 return Err(super::last_error())
296             }
297
298             loop {
299                 let mut status = 0;
300                 if GetExitCodeProcess(process, &mut status) == FALSE {
301                     let err = Err(super::last_error());
302                     assert!(CloseHandle(process) != 0);
303                     return err;
304                 }
305                 if status != STILL_ACTIVE {
306                     assert!(CloseHandle(process) != 0);
307                     return Ok(ExitStatus(status as int));
308                 }
309                 let interval = if deadline == 0 {
310                     INFINITE
311                 } else {
312                     let now = timer::now();
313                     if deadline < now {0} else {(deadline - now) as u32}
314                 };
315                 match WaitForSingleObject(process, interval) {
316                     WAIT_OBJECT_0 => {}
317                     WAIT_TIMEOUT => {
318                         assert!(CloseHandle(process) != 0);
319                         return Err(timeout("process wait timed out"))
320                     }
321                     _ => {
322                         let err = Err(super::last_error());
323                         assert!(CloseHandle(process) != 0);
324                         return err
325                     }
326                 }
327             }
328         }
329     }
330 }
331
332 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
333     libc::types::os::arch::extra::STARTUPINFO {
334         cb: 0,
335         lpReserved: ptr::null_mut(),
336         lpDesktop: ptr::null_mut(),
337         lpTitle: ptr::null_mut(),
338         dwX: 0,
339         dwY: 0,
340         dwXSize: 0,
341         dwYSize: 0,
342         dwXCountChars: 0,
343         dwYCountCharts: 0,
344         dwFillAttribute: 0,
345         dwFlags: 0,
346         wShowWindow: 0,
347         cbReserved2: 0,
348         lpReserved2: ptr::null_mut(),
349         hStdInput: libc::INVALID_HANDLE_VALUE,
350         hStdOutput: libc::INVALID_HANDLE_VALUE,
351         hStdError: libc::INVALID_HANDLE_VALUE,
352     }
353 }
354
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(),
359         dwProcessId: 0,
360         dwThreadId: 0
361     }
362 }
363
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() {
369         cmd.push(' ');
370         append_arg(&mut cmd, arg.as_str()
371                                 .expect("expected argument to be utf-8 encoded"));
372     }
373     return cmd;
374
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;
380         if quote {
381             cmd.push('"');
382         }
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);
386         }
387         if quote {
388             cmd.push('"');
389         }
390     }
391
392     fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
393         match arg[i] {
394             '"' => {
395                 // Escape quotes.
396                 cmd.push_str("\\\"");
397             }
398             '\\' => {
399                 if backslash_run_ends_in_quote(arg, i) {
400                     // Double all backslashes that are in runs before quotes.
401                     cmd.push_str("\\\\");
402                 } else {
403                     // Pass other backslashes through unescaped.
404                     cmd.push('\\');
405                 }
406             }
407             c => {
408                 cmd.push(c);
409             }
410         }
411     }
412
413     fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
414         while i < s.len() && s[i] == '\\' {
415             i += 1;
416         }
417         return i < s.len() && s[i] == '"';
418     }
419 }
420
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,
423 {
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
426     // \0 to terminate.
427     match env {
428         Some(env) => {
429             let mut blk = Vec::new();
430
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());
436                 blk.push(0);
437             }
438
439             blk.push(0);
440
441             cb(blk.as_mut_ptr() as *mut c_void)
442         }
443         _ => cb(ptr::null_mut())
444     }
445 }
446
447 fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
448     F: FnOnce(*const u16) -> T,
449 {
450     match d {
451       Some(dir) => {
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();
455           dir_str.push(0);
456           cb(dir_str.as_ptr())
457       },
458       None => cb(ptr::null())
459     }
460 }
461
462 fn free_handle(handle: *mut ()) {
463     assert!(unsafe {
464         libc::CloseHandle(mem::transmute(handle)) != 0
465     })
466 }
467
468 #[cfg(test)]
469 mod tests {
470     use c_str::ToCStr;
471
472     #[test]
473     fn test_make_command_line() {
474         use prelude::v1::*;
475         use str;
476         use c_str::CString;
477         use super::make_command_line;
478
479         fn test_wrapper(prog: &str, args: &[&str]) -> String {
480             make_command_line(&prog.to_c_str(),
481                               args.iter()
482                                   .map(|a| a.to_c_str())
483                                   .collect::<Vec<CString>>()
484                                   .as_slice())
485         }
486
487         assert_eq!(
488             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
489             "prog aaa bbb ccc"
490         );
491
492         assert_eq!(
493             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
494             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
495         );
496         assert_eq!(
497             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
498             "\"C:\\Program Files\\test\" aa\\\"bb"
499         );
500         assert_eq!(
501             test_wrapper("echo", &["a b c"]),
502             "echo \"a b c\""
503         );
504         assert_eq!(
505             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
506             "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
507         );
508     }
509 }