]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[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 #[cfg(stage0)] use collections::hash_map::Hasher;
14 use collections;
15 use env;
16 use ffi::CString;
17 use hash::Hash;
18 use libc::{pid_t, c_void};
19 use libc;
20 use mem;
21 use old_io::fs::PathExtensions;
22 use old_io::process::{ProcessExit, ExitStatus};
23 use old_io::{IoResult, IoError};
24 use old_io;
25 use os;
26 use old_path::BytesContainer;
27 use ptr;
28 use str;
29 use sync::{StaticMutex, MUTEX_INIT};
30 use sys::fs::FileDesc;
31
32 use sys::timer;
33 use sys_common::{AsInner, timeout};
34
35 pub use sys_common::ProcessConfig;
36
37 // `CreateProcess` is racy!
38 // http://support.microsoft.com/kb/315939
39 static CREATE_PROCESS_LOCK: StaticMutex = MUTEX_INIT;
40
41 /// A value representing a child process.
42 ///
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.
46 pub struct Process {
47     /// The unique id of the process (this should never be negative).
48     pid: pid_t,
49
50     /// A HANDLE to the process, which will prevent the pid being
51     /// re-used until the handle is closed.
52     handle: *mut (),
53 }
54
55 impl Drop for Process {
56     fn drop(&mut self) {
57         free_handle(self.handle);
58     }
59 }
60
61 impl Process {
62     pub fn id(&self) -> pid_t {
63         self.pid
64     }
65
66     pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
67         Process::killpid(self.pid, signal)
68     }
69
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);
74         if handle.is_null() {
75             return Err(super::last_error())
76         }
77         let ret = match signal {
78             // test for existence on signal 0
79             0 => {
80                 let mut status = 0;
81                 let ret = libc::GetExitCodeProcess(handle, &mut status);
82                 if ret == 0 {
83                     Err(super::last_error())
84                 } else if status != libc::STILL_ACTIVE {
85                     Err(IoError {
86                         kind: old_io::InvalidInput,
87                         desc: "no process to kill",
88                         detail: None,
89                     })
90                 } else {
91                     Ok(())
92                 }
93             }
94             15 | 9 => { // sigterm or sigkill
95                 let ret = libc::TerminateProcess(handle, 1);
96                 super::mkerr_winbool(ret)
97             }
98             _ => Err(IoError {
99                 kind: old_io::IoUnavailable,
100                 desc: "unsupported signal on windows",
101                 detail: None,
102             })
103         };
104         let _ = libc::CloseHandle(handle);
105         return ret;
106     }
107
108     #[allow(deprecated)]
109     #[cfg(stage0)]
110     pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
111                               out_fd: Option<P>, err_fd: Option<P>)
112                               -> IoResult<Process>
113         where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
114               K: BytesContainer + Eq + Hash<Hasher>, V: BytesContainer
115     {
116         use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
117         use libc::consts::os::extra::{
118             TRUE, FALSE,
119             STARTF_USESTDHANDLES,
120             INVALID_HANDLE_VALUE,
121             DUPLICATE_SAME_ACCESS
122         };
123         use libc::funcs::extra::kernel32::{
124             GetCurrentProcess,
125             DuplicateHandle,
126             CloseHandle,
127             CreateProcessW
128         };
129         use libc::funcs::extra::msvcrt::get_osfhandle;
130
131         use mem;
132         use iter::IteratorExt;
133         use str::StrExt;
134
135         if cfg.gid().is_some() || cfg.uid().is_some() {
136             return Err(IoError {
137                 kind: old_io::IoUnavailable,
138                 desc: "unsupported gid/uid requested on windows",
139                 detail: None,
140             })
141         }
142
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 }
148
149                 // Split the value and test each path to see if the
150                 // program exists.
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);
154                     if path.exists() {
155                         return Some(CString::from_slice(path.as_vec()))
156                     }
157                 }
158                 break
159             }
160             None
161         });
162
163         unsafe {
164             let mut si = zeroed_startupinfo();
165             si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
166             si.dwFlags = STARTF_USESTDHANDLES;
167
168             let cur_proc = GetCurrentProcess();
169
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,
174                           is_stdin: bool| {
175                 match *fd {
176                     None => {
177                         let access = if is_stdin {
178                             libc::FILE_GENERIC_READ
179                         } else {
180                             libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
181                         };
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(),
186                             bInheritHandle: 1,
187                         };
188                         let mut filename: Vec<u16> = "NUL".utf16_units().collect();
189                         filename.push(0);
190                         *slot = libc::CreateFileW(filename.as_ptr(),
191                                                   access,
192                                                   libc::FILE_SHARE_READ |
193                                                       libc::FILE_SHARE_WRITE,
194                                                   &mut sa,
195                                                   libc::OPEN_EXISTING,
196                                                   0,
197                                                   ptr::null_mut());
198                         if *slot == INVALID_HANDLE_VALUE {
199                             return Err(super::last_error())
200                         }
201                     }
202                     Some(ref fd) => {
203                         let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
204                         if orig == INVALID_HANDLE_VALUE {
205                             return Err(super::last_error())
206                         }
207                         if DuplicateHandle(cur_proc, orig, cur_proc, slot,
208                                            0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
209                             return Err(super::last_error())
210                         }
211                     }
212                 }
213                 Ok(())
214             };
215
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));
219
220             let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
221                                             cfg.args());
222             let mut pi = zeroed_process_information();
223             let mut create_err = None;
224
225             // stolen from the libuv code.
226             let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
227             if cfg.detach() {
228                 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
229             }
230
231             with_envp(cfg.env(), |envp| {
232                 with_dirp(cfg.cwd(), |dirp| {
233                     let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
234                     cmd_str.push(0);
235                     let _lock = CREATE_PROCESS_LOCK.lock().unwrap();
236                     let created = CreateProcessW(ptr::null(),
237                                                  cmd_str.as_mut_ptr(),
238                                                  ptr::null_mut(),
239                                                  ptr::null_mut(),
240                                                  TRUE,
241                                                  flags, envp, dirp,
242                                                  &mut si, &mut pi);
243                     if created == FALSE {
244                         create_err = Some(super::last_error());
245                     }
246                 })
247             });
248
249             assert!(CloseHandle(si.hStdInput) != 0);
250             assert!(CloseHandle(si.hStdOutput) != 0);
251             assert!(CloseHandle(si.hStdError) != 0);
252
253             match create_err {
254                 Some(err) => return Err(err),
255                 None => {}
256             }
257
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);
264
265             Ok(Process {
266                 pid: pi.dwProcessId as pid_t,
267                 handle: pi.hProcess as *mut ()
268             })
269         }
270     }
271     #[allow(deprecated)]
272     #[cfg(not(stage0))]
273     pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
274                               out_fd: Option<P>, err_fd: Option<P>)
275                               -> IoResult<Process>
276         where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
277               K: BytesContainer + Eq + Hash, V: BytesContainer
278     {
279         use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
280         use libc::consts::os::extra::{
281             TRUE, FALSE,
282             STARTF_USESTDHANDLES,
283             INVALID_HANDLE_VALUE,
284             DUPLICATE_SAME_ACCESS
285         };
286         use libc::funcs::extra::kernel32::{
287             GetCurrentProcess,
288             DuplicateHandle,
289             CloseHandle,
290             CreateProcessW
291         };
292         use libc::funcs::extra::msvcrt::get_osfhandle;
293
294         use mem;
295         use iter::IteratorExt;
296         use str::StrExt;
297
298         if cfg.gid().is_some() || cfg.uid().is_some() {
299             return Err(IoError {
300                 kind: old_io::IoUnavailable,
301                 desc: "unsupported gid/uid requested on windows",
302                 detail: None,
303             })
304         }
305
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 }
311
312                 // Split the value and test each path to see if the
313                 // program exists.
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);
317                     if path.exists() {
318                         return Some(CString::from_slice(path.as_vec()))
319                     }
320                 }
321                 break
322             }
323             None
324         });
325
326         unsafe {
327             let mut si = zeroed_startupinfo();
328             si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
329             si.dwFlags = STARTF_USESTDHANDLES;
330
331             let cur_proc = GetCurrentProcess();
332
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,
337                           is_stdin: bool| {
338                 match *fd {
339                     None => {
340                         let access = if is_stdin {
341                             libc::FILE_GENERIC_READ
342                         } else {
343                             libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
344                         };
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(),
349                             bInheritHandle: 1,
350                         };
351                         let mut filename: Vec<u16> = "NUL".utf16_units().collect();
352                         filename.push(0);
353                         *slot = libc::CreateFileW(filename.as_ptr(),
354                                                   access,
355                                                   libc::FILE_SHARE_READ |
356                                                       libc::FILE_SHARE_WRITE,
357                                                   &mut sa,
358                                                   libc::OPEN_EXISTING,
359                                                   0,
360                                                   ptr::null_mut());
361                         if *slot == INVALID_HANDLE_VALUE {
362                             return Err(super::last_error())
363                         }
364                     }
365                     Some(ref fd) => {
366                         let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE;
367                         if orig == INVALID_HANDLE_VALUE {
368                             return Err(super::last_error())
369                         }
370                         if DuplicateHandle(cur_proc, orig, cur_proc, slot,
371                                            0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
372                             return Err(super::last_error())
373                         }
374                     }
375                 }
376                 Ok(())
377             };
378
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));
382
383             let cmd_str = make_command_line(program.as_ref().unwrap_or(cfg.program()),
384                                             cfg.args());
385             let mut pi = zeroed_process_information();
386             let mut create_err = None;
387
388             // stolen from the libuv code.
389             let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
390             if cfg.detach() {
391                 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
392             }
393
394             with_envp(cfg.env(), |envp| {
395                 with_dirp(cfg.cwd(), |dirp| {
396                     let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect();
397                     cmd_str.push(0);
398                     let _lock = CREATE_PROCESS_LOCK.lock().unwrap();
399                     let created = CreateProcessW(ptr::null(),
400                                                  cmd_str.as_mut_ptr(),
401                                                  ptr::null_mut(),
402                                                  ptr::null_mut(),
403                                                  TRUE,
404                                                  flags, envp, dirp,
405                                                  &mut si, &mut pi);
406                     if created == FALSE {
407                         create_err = Some(super::last_error());
408                     }
409                 })
410             });
411
412             assert!(CloseHandle(si.hStdInput) != 0);
413             assert!(CloseHandle(si.hStdOutput) != 0);
414             assert!(CloseHandle(si.hStdError) != 0);
415
416             match create_err {
417                 Some(err) => return Err(err),
418                 None => {}
419             }
420
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);
427
428             Ok(Process {
429                 pid: pi.dwProcessId as pid_t,
430                 handle: pi.hProcess as *mut ()
431             })
432         }
433     }
434
435     /// Waits for a process to exit and returns the exit code, failing
436     /// if there is no process with the specified id.
437     ///
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::{
446             SYNCHRONIZE,
447             PROCESS_QUERY_INFORMATION,
448             FALSE,
449             STILL_ACTIVE,
450             INFINITE,
451             WAIT_TIMEOUT,
452             WAIT_OBJECT_0,
453         };
454         use libc::funcs::extra::kernel32::{
455             OpenProcess,
456             GetExitCodeProcess,
457             CloseHandle,
458             WaitForSingleObject,
459         };
460
461         unsafe {
462             let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
463                                       FALSE,
464                                       self.pid as DWORD);
465             if process.is_null() {
466                 return Err(super::last_error())
467             }
468
469             loop {
470                 let mut status = 0;
471                 if GetExitCodeProcess(process, &mut status) == FALSE {
472                     let err = Err(super::last_error());
473                     assert!(CloseHandle(process) != 0);
474                     return err;
475                 }
476                 if status != STILL_ACTIVE {
477                     assert!(CloseHandle(process) != 0);
478                     return Ok(ExitStatus(status as int));
479                 }
480                 let interval = if deadline == 0 {
481                     INFINITE
482                 } else {
483                     let now = timer::now();
484                     if deadline < now {0} else {(deadline - now) as u32}
485                 };
486                 match WaitForSingleObject(process, interval) {
487                     WAIT_OBJECT_0 => {}
488                     WAIT_TIMEOUT => {
489                         assert!(CloseHandle(process) != 0);
490                         return Err(timeout("process wait timed out"))
491                     }
492                     _ => {
493                         let err = Err(super::last_error());
494                         assert!(CloseHandle(process) != 0);
495                         return err
496                     }
497                 }
498             }
499         }
500     }
501 }
502
503 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
504     libc::types::os::arch::extra::STARTUPINFO {
505         cb: 0,
506         lpReserved: ptr::null_mut(),
507         lpDesktop: ptr::null_mut(),
508         lpTitle: ptr::null_mut(),
509         dwX: 0,
510         dwY: 0,
511         dwXSize: 0,
512         dwYSize: 0,
513         dwXCountChars: 0,
514         dwYCountCharts: 0,
515         dwFillAttribute: 0,
516         dwFlags: 0,
517         wShowWindow: 0,
518         cbReserved2: 0,
519         lpReserved2: ptr::null_mut(),
520         hStdInput: libc::INVALID_HANDLE_VALUE,
521         hStdOutput: libc::INVALID_HANDLE_VALUE,
522         hStdError: libc::INVALID_HANDLE_VALUE,
523     }
524 }
525
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(),
530         dwProcessId: 0,
531         dwThreadId: 0
532     }
533 }
534
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"));
539     for arg in args {
540         cmd.push(' ');
541         append_arg(&mut cmd, str::from_utf8(arg.as_bytes()).ok()
542                                 .expect("expected argument to be utf-8 encoded"));
543     }
544     return cmd;
545
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;
551         if quote {
552             cmd.push('"');
553         }
554         let argvec: Vec<char> = arg.chars().collect();
555         for i in 0..argvec.len() {
556             append_char_at(cmd, &argvec, i);
557         }
558         if quote {
559             cmd.push('"');
560         }
561     }
562
563     fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
564         match arg[i] {
565             '"' => {
566                 // Escape quotes.
567                 cmd.push_str("\\\"");
568             }
569             '\\' => {
570                 if backslash_run_ends_in_quote(arg, i) {
571                     // Double all backslashes that are in runs before quotes.
572                     cmd.push_str("\\\\");
573                 } else {
574                     // Pass other backslashes through unescaped.
575                     cmd.push('\\');
576                 }
577             }
578             c => {
579                 cmd.push(c);
580             }
581         }
582     }
583
584     fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
585         while i < s.len() && s[i] == '\\' {
586             i += 1;
587         }
588         return i < s.len() && s[i] == '"';
589     }
590 }
591
592 #[cfg(stage0)]
593 fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T
594     where K: BytesContainer + Eq + Hash<Hasher>,
595           V: BytesContainer,
596           F: FnOnce(*mut c_void) -> T,
597 {
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
600     // \0 to terminate.
601     match env {
602         Some(env) => {
603             let mut blk = Vec::new();
604
605             for pair in env {
606                 let kv = format!("{}={}",
607                                  pair.0.container_as_str().unwrap(),
608                                  pair.1.container_as_str().unwrap());
609                 blk.extend(kv.utf16_units());
610                 blk.push(0);
611             }
612
613             blk.push(0);
614
615             cb(blk.as_mut_ptr() as *mut c_void)
616         }
617         _ => cb(ptr::null_mut())
618     }
619 }
620 #[cfg(not(stage0))]
621 fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T
622     where K: BytesContainer + Eq + Hash,
623           V: BytesContainer,
624           F: FnOnce(*mut c_void) -> T,
625 {
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
628     // \0 to terminate.
629     match env {
630         Some(env) => {
631             let mut blk = Vec::new();
632
633             for pair in env {
634                 let kv = format!("{}={}",
635                                  pair.0.container_as_str().unwrap(),
636                                  pair.1.container_as_str().unwrap());
637                 blk.extend(kv.utf16_units());
638                 blk.push(0);
639             }
640
641             blk.push(0);
642
643             cb(blk.as_mut_ptr() as *mut c_void)
644         }
645         _ => cb(ptr::null_mut())
646     }
647 }
648
649 fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
650     F: FnOnce(*const u16) -> T,
651 {
652     match d {
653       Some(dir) => {
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();
657           dir_str.push(0);
658           cb(dir_str.as_ptr())
659       },
660       None => cb(ptr::null())
661     }
662 }
663
664 fn free_handle(handle: *mut ()) {
665     assert!(unsafe {
666         libc::CloseHandle(mem::transmute(handle)) != 0
667     })
668 }
669
670 #[cfg(test)]
671 mod tests {
672     use prelude::v1::*;
673     use str;
674     use ffi::CString;
675     use super::make_command_line;
676
677     #[test]
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()),
681                               &args.iter()
682                                    .map(|a| CString::from_slice(a.as_bytes()))
683                                    .collect::<Vec<CString>>())
684         }
685
686         assert_eq!(
687             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
688             "prog aaa bbb ccc"
689         );
690
691         assert_eq!(
692             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
693             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
694         );
695         assert_eq!(
696             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
697             "\"C:\\Program Files\\test\" aa\\\"bb"
698         );
699         assert_eq!(
700             test_wrapper("echo", &["a b c"]),
701             "echo \"a b c\""
702         );
703         assert_eq!(
704             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
705             "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
706         );
707     }
708 }