]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/process.rs
auto merge of #14932 : Sawyer47/rust/json-smallfix, r=huonw
[rust.git] / src / libnative / io / 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 libc::{pid_t, c_void, c_int};
12 use libc;
13 use std::mem;
14 use std::os;
15 use std::ptr;
16 use std::rt::rtio;
17 use std::rt::rtio::{ProcessConfig, IoResult, IoError};
18 use std::c_str::CString;
19
20 use super::file;
21 use super::util;
22
23 #[cfg(windows)] use std::string::String;
24 #[cfg(unix)] use super::c;
25 #[cfg(unix)] use super::retry;
26 #[cfg(unix)] use io::helper_thread::Helper;
27
28 #[cfg(unix)]
29 helper_init!(static mut HELPER: Helper<Req>)
30
31 /**
32  * A value representing a child process.
33  *
34  * The lifetime of this value is linked to the lifetime of the actual
35  * process - the Process destructor calls self.finish() which waits
36  * for the process to terminate.
37  */
38 pub struct Process {
39     /// The unique id of the process (this should never be negative).
40     pid: pid_t,
41
42     /// A handle to the process - on unix this will always be NULL, but on
43     /// windows it will be a HANDLE to the process, which will prevent the
44     /// pid being re-used until the handle is closed.
45     handle: *(),
46
47     /// None until finish() is called.
48     exit_code: Option<rtio::ProcessExit>,
49
50     /// Manually delivered signal
51     exit_signal: Option<int>,
52
53     /// Deadline after which wait() will return
54     deadline: u64,
55 }
56
57 #[cfg(unix)]
58 enum Req {
59     NewChild(libc::pid_t, Sender<rtio::ProcessExit>, u64),
60 }
61
62 impl Process {
63     /// Creates a new process using native process-spawning abilities provided
64     /// by the OS. Operations on this process will be blocking instead of using
65     /// the runtime for sleeping just this current task.
66     pub fn spawn(cfg: ProcessConfig)
67         -> IoResult<(Process, Vec<Option<file::FileDesc>>)>
68     {
69         // right now we only handle stdin/stdout/stderr.
70         if cfg.extra_io.len() > 0 {
71             return Err(super::unimpl());
72         }
73
74         fn get_io(io: rtio::StdioContainer,
75                   ret: &mut Vec<Option<file::FileDesc>>)
76             -> (Option<os::Pipe>, c_int)
77         {
78             match io {
79                 rtio::Ignored => { ret.push(None); (None, -1) }
80                 rtio::InheritFd(fd) => { ret.push(None); (None, fd) }
81                 rtio::CreatePipe(readable, _writable) => {
82                     let pipe = os::pipe();
83                     let (theirs, ours) = if readable {
84                         (pipe.input, pipe.out)
85                     } else {
86                         (pipe.out, pipe.input)
87                     };
88                     ret.push(Some(file::FileDesc::new(ours, true)));
89                     (Some(pipe), theirs)
90                 }
91             }
92         }
93
94         let mut ret_io = Vec::new();
95         let (in_pipe, in_fd) = get_io(cfg.stdin, &mut ret_io);
96         let (out_pipe, out_fd) = get_io(cfg.stdout, &mut ret_io);
97         let (err_pipe, err_fd) = get_io(cfg.stderr, &mut ret_io);
98
99         let res = spawn_process_os(cfg, in_fd, out_fd, err_fd);
100
101         unsafe {
102             for pipe in in_pipe.iter() { let _ = libc::close(pipe.input); }
103             for pipe in out_pipe.iter() { let _ = libc::close(pipe.out); }
104             for pipe in err_pipe.iter() { let _ = libc::close(pipe.out); }
105         }
106
107         match res {
108             Ok(res) => {
109                 Ok((Process {
110                         pid: res.pid,
111                         handle: res.handle,
112                         exit_code: None,
113                         exit_signal: None,
114                         deadline: 0,
115                     },
116                     ret_io))
117             }
118             Err(e) => Err(e)
119         }
120     }
121
122     pub fn kill(pid: libc::pid_t, signum: int) -> IoResult<()> {
123         unsafe { killpid(pid, signum) }
124     }
125 }
126
127 impl rtio::RtioProcess for Process {
128     fn id(&self) -> pid_t { self.pid }
129
130     fn set_timeout(&mut self, timeout: Option<u64>) {
131         self.deadline = timeout.map(|i| i + ::io::timer::now()).unwrap_or(0);
132     }
133
134     fn wait(&mut self) -> IoResult<rtio::ProcessExit> {
135         match self.exit_code {
136             Some(code) => Ok(code),
137             None => {
138                 let code = try!(waitpid(self.pid, self.deadline));
139                 // On windows, waitpid will never return a signal. If a signal
140                 // was successfully delivered to the process, however, we can
141                 // consider it as having died via a signal.
142                 let code = match self.exit_signal {
143                     None => code,
144                     Some(signal) if cfg!(windows) => rtio::ExitSignal(signal),
145                     Some(..) => code,
146                 };
147                 self.exit_code = Some(code);
148                 Ok(code)
149             }
150         }
151     }
152
153     fn kill(&mut self, signum: int) -> IoResult<()> {
154         #[cfg(unix)] use ERROR = libc::EINVAL;
155         #[cfg(windows)] use ERROR = libc::ERROR_NOTHING_TO_TERMINATE;
156
157         // On linux (and possibly other unices), a process that has exited will
158         // continue to accept signals because it is "defunct". The delivery of
159         // signals will only fail once the child has been reaped. For this
160         // reason, if the process hasn't exited yet, then we attempt to collect
161         // their status with WNOHANG.
162         if self.exit_code.is_none() {
163             match waitpid_nowait(self.pid) {
164                 Some(code) => { self.exit_code = Some(code); }
165                 None => {}
166             }
167         }
168
169         // if the process has finished, and therefore had waitpid called,
170         // and we kill it, then on unix we might ending up killing a
171         // newer process that happens to have the same (re-used) id
172         match self.exit_code {
173             Some(..) => return Err(IoError {
174                 code: ERROR as uint,
175                 extra: 0,
176                 detail: Some("can't kill an exited process".to_str()),
177             }),
178             None => {}
179         }
180
181         // A successfully delivered signal that isn't 0 (just a poll for being
182         // alive) is recorded for windows (see wait())
183         match unsafe { killpid(self.pid, signum) } {
184             Ok(()) if signum == 0 => Ok(()),
185             Ok(()) => { self.exit_signal = Some(signum); Ok(()) }
186             Err(e) => Err(e),
187         }
188     }
189 }
190
191 impl Drop for Process {
192     fn drop(&mut self) {
193         free_handle(self.handle);
194     }
195 }
196
197 #[cfg(windows)]
198 unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
199     let handle = libc::OpenProcess(libc::PROCESS_TERMINATE |
200                                    libc::PROCESS_QUERY_INFORMATION,
201                                    libc::FALSE, pid as libc::DWORD);
202     if handle.is_null() {
203         return Err(super::last_error())
204     }
205     let ret = match signal {
206         // test for existence on signal 0
207         0 => {
208             let mut status = 0;
209             let ret = libc::GetExitCodeProcess(handle, &mut status);
210             if ret == 0 {
211                 Err(super::last_error())
212             } else if status != libc::STILL_ACTIVE {
213                 Err(IoError {
214                     code: libc::ERROR_NOTHING_TO_TERMINATE as uint,
215                     extra: 0,
216                     detail: None,
217                 })
218             } else {
219                 Ok(())
220             }
221         }
222         15 | 9 => { // sigterm or sigkill
223             let ret = libc::TerminateProcess(handle, 1);
224             super::mkerr_winbool(ret)
225         }
226         _ => Err(IoError {
227             code: libc::ERROR_CALL_NOT_IMPLEMENTED as uint,
228             extra: 0,
229             detail: Some("unsupported signal on windows".to_string()),
230         })
231     };
232     let _ = libc::CloseHandle(handle);
233     return ret;
234 }
235
236 #[cfg(not(windows))]
237 unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
238     let r = libc::funcs::posix88::signal::kill(pid, signal as c_int);
239     super::mkerr_libc(r)
240 }
241
242 struct SpawnProcessResult {
243     pid: pid_t,
244     handle: *(),
245 }
246
247 #[cfg(windows)]
248 fn spawn_process_os(cfg: ProcessConfig,
249                     in_fd: c_int, out_fd: c_int, err_fd: c_int)
250                  -> IoResult<SpawnProcessResult> {
251     use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
252     use libc::consts::os::extra::{
253         TRUE, FALSE,
254         STARTF_USESTDHANDLES,
255         INVALID_HANDLE_VALUE,
256         DUPLICATE_SAME_ACCESS
257     };
258     use libc::funcs::extra::kernel32::{
259         GetCurrentProcess,
260         DuplicateHandle,
261         CloseHandle,
262         CreateProcessW
263     };
264     use libc::funcs::extra::msvcrt::get_osfhandle;
265
266     use std::mem;
267
268     if cfg.gid.is_some() || cfg.uid.is_some() {
269         return Err(IoError {
270             code: libc::ERROR_CALL_NOT_IMPLEMENTED as uint,
271             extra: 0,
272             detail: Some("unsupported gid/uid requested on windows".to_str()),
273         })
274     }
275
276     unsafe {
277         let mut si = zeroed_startupinfo();
278         si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
279         si.dwFlags = STARTF_USESTDHANDLES;
280
281         let cur_proc = GetCurrentProcess();
282
283         // Similarly to unix, we don't actually leave holes for the stdio file
284         // descriptors, but rather open up /dev/null equivalents. These
285         // equivalents are drawn from libuv's windows process spawning.
286         let set_fd = |fd: c_int, slot: &mut HANDLE, is_stdin: bool| {
287             if fd == -1 {
288                 let access = if is_stdin {
289                     libc::FILE_GENERIC_READ
290                 } else {
291                     libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
292                 };
293                 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
294                 let mut sa = libc::SECURITY_ATTRIBUTES {
295                     nLength: size as libc::DWORD,
296                     lpSecurityDescriptor: ptr::mut_null(),
297                     bInheritHandle: 1,
298                 };
299                 let filename = "NUL".to_utf16().append_one(0);
300                 *slot = libc::CreateFileW(filename.as_ptr(),
301                                           access,
302                                           libc::FILE_SHARE_READ |
303                                               libc::FILE_SHARE_WRITE,
304                                           &mut sa,
305                                           libc::OPEN_EXISTING,
306                                           0,
307                                           ptr::mut_null());
308                 if *slot == INVALID_HANDLE_VALUE as libc::HANDLE {
309                     return Err(super::last_error())
310                 }
311             } else {
312                 let orig = get_osfhandle(fd) as HANDLE;
313                 if orig == INVALID_HANDLE_VALUE as HANDLE {
314                     return Err(super::last_error())
315                 }
316                 if DuplicateHandle(cur_proc, orig, cur_proc, slot,
317                                    0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
318                     return Err(super::last_error())
319                 }
320             }
321             Ok(())
322         };
323
324         try!(set_fd(in_fd, &mut si.hStdInput, true));
325         try!(set_fd(out_fd, &mut si.hStdOutput, false));
326         try!(set_fd(err_fd, &mut si.hStdError, false));
327
328         let cmd_str = make_command_line(cfg.program, cfg.args);
329         let mut pi = zeroed_process_information();
330         let mut create_err = None;
331
332         // stolen from the libuv code.
333         let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
334         if cfg.detach {
335             flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
336         }
337
338         with_envp(cfg.env, |envp| {
339             with_dirp(cfg.cwd, |dirp| {
340                 let mut cmd_str = cmd_str.to_utf16().append_one(0);
341                 let created = CreateProcessW(ptr::null(),
342                                              cmd_str.as_mut_ptr(),
343                                              ptr::mut_null(),
344                                              ptr::mut_null(),
345                                              TRUE,
346                                              flags, envp, dirp,
347                                              &mut si, &mut pi);
348                 if created == FALSE {
349                     create_err = Some(super::last_error());
350                 }
351             })
352         });
353
354         assert!(CloseHandle(si.hStdInput) != 0);
355         assert!(CloseHandle(si.hStdOutput) != 0);
356         assert!(CloseHandle(si.hStdError) != 0);
357
358         match create_err {
359             Some(err) => return Err(err),
360             None => {}
361         }
362
363         // We close the thread handle because we don't care about keeping the
364         // thread id valid, and we aren't keeping the thread handle around to be
365         // able to close it later. We don't close the process handle however
366         // because std::we want the process id to stay valid at least until the
367         // calling code closes the process handle.
368         assert!(CloseHandle(pi.hThread) != 0);
369
370         Ok(SpawnProcessResult {
371             pid: pi.dwProcessId as pid_t,
372             handle: pi.hProcess as *()
373         })
374     }
375 }
376
377 #[cfg(windows)]
378 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
379     libc::types::os::arch::extra::STARTUPINFO {
380         cb: 0,
381         lpReserved: ptr::mut_null(),
382         lpDesktop: ptr::mut_null(),
383         lpTitle: ptr::mut_null(),
384         dwX: 0,
385         dwY: 0,
386         dwXSize: 0,
387         dwYSize: 0,
388         dwXCountChars: 0,
389         dwYCountCharts: 0,
390         dwFillAttribute: 0,
391         dwFlags: 0,
392         wShowWindow: 0,
393         cbReserved2: 0,
394         lpReserved2: ptr::mut_null(),
395         hStdInput: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
396         hStdOutput: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
397         hStdError: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
398     }
399 }
400
401 #[cfg(windows)]
402 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
403     libc::types::os::arch::extra::PROCESS_INFORMATION {
404         hProcess: ptr::mut_null(),
405         hThread: ptr::mut_null(),
406         dwProcessId: 0,
407         dwThreadId: 0
408     }
409 }
410
411 #[cfg(windows)]
412 fn make_command_line(prog: &CString, args: &[CString]) -> String {
413     let mut cmd = String::new();
414     append_arg(&mut cmd, prog.as_str()
415                              .expect("expected program name to be utf-8 encoded"));
416     for arg in args.iter() {
417         cmd.push_char(' ');
418         append_arg(&mut cmd, arg.as_str()
419                                 .expect("expected argument to be utf-8 encoded"));
420     }
421     return cmd;
422
423     fn append_arg(cmd: &mut String, arg: &str) {
424         let quote = arg.chars().any(|c| c == ' ' || c == '\t');
425         if quote {
426             cmd.push_char('"');
427         }
428         let argvec: Vec<char> = arg.chars().collect();
429         for i in range(0u, argvec.len()) {
430             append_char_at(cmd, &argvec, i);
431         }
432         if quote {
433             cmd.push_char('"');
434         }
435     }
436
437     fn append_char_at(cmd: &mut String, arg: &Vec<char>, i: uint) {
438         match *arg.get(i) {
439             '"' => {
440                 // Escape quotes.
441                 cmd.push_str("\\\"");
442             }
443             '\\' => {
444                 if backslash_run_ends_in_quote(arg, i) {
445                     // Double all backslashes that are in runs before quotes.
446                     cmd.push_str("\\\\");
447                 } else {
448                     // Pass other backslashes through unescaped.
449                     cmd.push_char('\\');
450                 }
451             }
452             c => {
453                 cmd.push_char(c);
454             }
455         }
456     }
457
458     fn backslash_run_ends_in_quote(s: &Vec<char>, mut i: uint) -> bool {
459         while i < s.len() && *s.get(i) == '\\' {
460             i += 1;
461         }
462         return i < s.len() && *s.get(i) == '"';
463     }
464 }
465
466 #[cfg(unix)]
467 fn spawn_process_os(cfg: ProcessConfig, in_fd: c_int, out_fd: c_int, err_fd: c_int)
468                 -> IoResult<SpawnProcessResult>
469 {
470     use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
471     use libc::funcs::bsd44::getdtablesize;
472     use io::c;
473
474     mod rustrt {
475         extern {
476             pub fn rust_unset_sigprocmask();
477         }
478     }
479
480     #[cfg(target_os = "macos")]
481     unsafe fn set_environ(envp: *c_void) {
482         extern { fn _NSGetEnviron() -> *mut *c_void; }
483
484         *_NSGetEnviron() = envp;
485     }
486     #[cfg(not(target_os = "macos"))]
487     unsafe fn set_environ(envp: *c_void) {
488         extern { static mut environ: *c_void; }
489         environ = envp;
490     }
491
492     unsafe fn set_cloexec(fd: c_int) {
493         let ret = c::ioctl(fd, c::FIOCLEX);
494         assert_eq!(ret, 0);
495     }
496
497     let dirp = cfg.cwd.map(|c| c.with_ref(|p| p)).unwrap_or(ptr::null());
498
499     with_envp(cfg.env, proc(envp) {
500         with_argv(cfg.program, cfg.args, proc(argv) unsafe {
501             let pipe = os::pipe();
502             let mut input = file::FileDesc::new(pipe.input, true);
503             let mut output = file::FileDesc::new(pipe.out, true);
504
505             // We may use this in the child, so perform allocations before the
506             // fork
507             let devnull = "/dev/null".to_c_str();
508
509             set_cloexec(output.fd());
510
511             let pid = fork();
512             if pid < 0 {
513                 fail!("failure in fork: {}", os::last_os_error());
514             } else if pid > 0 {
515                 drop(output);
516                 let mut bytes = [0, ..4];
517                 return match input.inner_read(bytes) {
518                     Ok(4) => {
519                         let errno = (bytes[0] << 24) as i32 |
520                                     (bytes[1] << 16) as i32 |
521                                     (bytes[2] <<  8) as i32 |
522                                     (bytes[3] <<  0) as i32;
523                         Err(IoError {
524                             code: errno as uint,
525                             detail: None,
526                             extra: 0,
527                         })
528                     }
529                     Err(..) => {
530                         Ok(SpawnProcessResult {
531                             pid: pid,
532                             handle: ptr::null()
533                         })
534                     }
535                     Ok(..) => fail!("short read on the cloexec pipe"),
536                 };
537             }
538             // And at this point we've reached a special time in the life of the
539             // child. The child must now be considered hamstrung and unable to
540             // do anything other than syscalls really. Consider the following
541             // scenario:
542             //
543             //      1. Thread A of process 1 grabs the malloc() mutex
544             //      2. Thread B of process 1 forks(), creating thread C
545             //      3. Thread C of process 2 then attempts to malloc()
546             //      4. The memory of process 2 is the same as the memory of
547             //         process 1, so the mutex is locked.
548             //
549             // This situation looks a lot like deadlock, right? It turns out
550             // that this is what pthread_atfork() takes care of, which is
551             // presumably implemented across platforms. The first thing that
552             // threads to *before* forking is to do things like grab the malloc
553             // mutex, and then after the fork they unlock it.
554             //
555             // Despite this information, libnative's spawn has been witnessed to
556             // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
557             // all collected backtraces point at malloc/free traffic in the
558             // child spawned process.
559             //
560             // For this reason, the block of code below should contain 0
561             // invocations of either malloc of free (or their related friends).
562             //
563             // As an example of not having malloc/free traffic, we don't close
564             // this file descriptor by dropping the FileDesc (which contains an
565             // allocation). Instead we just close it manually. This will never
566             // have the drop glue anyway because this code never returns (the
567             // child will either exec() or invoke libc::exit)
568             let _ = libc::close(input.fd());
569
570             fn fail(output: &mut file::FileDesc) -> ! {
571                 let errno = os::errno();
572                 let bytes = [
573                     (errno << 24) as u8,
574                     (errno << 16) as u8,
575                     (errno <<  8) as u8,
576                     (errno <<  0) as u8,
577                 ];
578                 assert!(output.inner_write(bytes).is_ok());
579                 unsafe { libc::_exit(1) }
580             }
581
582             rustrt::rust_unset_sigprocmask();
583
584             // If a stdio file descriptor is set to be ignored (via a -1 file
585             // descriptor), then we don't actually close it, but rather open
586             // up /dev/null into that file descriptor. Otherwise, the first file
587             // descriptor opened up in the child would be numbered as one of the
588             // stdio file descriptors, which is likely to wreak havoc.
589             let setup = |src: c_int, dst: c_int| {
590                 let src = if src == -1 {
591                     let flags = if dst == libc::STDIN_FILENO {
592                         libc::O_RDONLY
593                     } else {
594                         libc::O_RDWR
595                     };
596                     devnull.with_ref(|p| libc::open(p, flags, 0))
597                 } else {
598                     src
599                 };
600                 src != -1 && retry(|| dup2(src, dst)) != -1
601             };
602
603             if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
604             if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
605             if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
606
607             // close all other fds
608             for fd in range(3, getdtablesize()).rev() {
609                 if fd != output.fd() {
610                     let _ = close(fd as c_int);
611                 }
612             }
613
614             match cfg.gid {
615                 Some(u) => {
616                     if libc::setgid(u as libc::gid_t) != 0 {
617                         fail(&mut output);
618                     }
619                 }
620                 None => {}
621             }
622             match cfg.uid {
623                 Some(u) => {
624                     // When dropping privileges from root, the `setgroups` call will
625                     // remove any extraneous groups. If we don't call this, then
626                     // even though our uid has dropped, we may still have groups
627                     // that enable us to do super-user things. This will fail if we
628                     // aren't root, so don't bother checking the return value, this
629                     // is just done as an optimistic privilege dropping function.
630                     extern {
631                         fn setgroups(ngroups: libc::c_int,
632                                      ptr: *libc::c_void) -> libc::c_int;
633                     }
634                     let _ = setgroups(0, 0 as *libc::c_void);
635
636                     if libc::setuid(u as libc::uid_t) != 0 {
637                         fail(&mut output);
638                     }
639                 }
640                 None => {}
641             }
642             if cfg.detach {
643                 // Don't check the error of setsid because it fails if we're the
644                 // process leader already. We just forked so it shouldn't return
645                 // error, but ignore it anyway.
646                 let _ = libc::setsid();
647             }
648             if !dirp.is_null() && chdir(dirp) == -1 {
649                 fail(&mut output);
650             }
651             if !envp.is_null() {
652                 set_environ(envp);
653             }
654             let _ = execvp(*argv, argv);
655             fail(&mut output);
656         })
657     })
658 }
659
660 #[cfg(unix)]
661 fn with_argv<T>(prog: &CString, args: &[CString], cb: proc(**libc::c_char) -> T) -> T {
662     let mut ptrs: Vec<*libc::c_char> = Vec::with_capacity(args.len()+1);
663
664     // Convert the CStrings into an array of pointers. Note: the
665     // lifetime of the various CStrings involved is guaranteed to be
666     // larger than the lifetime of our invocation of cb, but this is
667     // technically unsafe as the callback could leak these pointers
668     // out of our scope.
669     ptrs.push(prog.with_ref(|buf| buf));
670     ptrs.extend(args.iter().map(|tmp| tmp.with_ref(|buf| buf)));
671
672     // Add a terminating null pointer (required by libc).
673     ptrs.push(ptr::null());
674
675     cb(ptrs.as_ptr())
676 }
677
678 #[cfg(unix)]
679 fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: proc(*c_void) -> T) -> T {
680     // On posixy systems we can pass a char** for envp, which is a
681     // null-terminated array of "k=v\0" strings. Since we must create
682     // these strings locally, yet expose a raw pointer to them, we
683     // create a temporary vector to own the CStrings that outlives the
684     // call to cb.
685     match env {
686         Some(env) => {
687             let mut tmps = Vec::with_capacity(env.len());
688
689             for pair in env.iter() {
690                 let mut kv = Vec::new();
691                 kv.push_all(pair.ref0().as_bytes_no_nul());
692                 kv.push('=' as u8);
693                 kv.push_all(pair.ref1().as_bytes()); // includes terminal \0
694                 tmps.push(kv);
695             }
696
697             // As with `with_argv`, this is unsafe, since cb could leak the pointers.
698             let mut ptrs: Vec<*libc::c_char> =
699                 tmps.iter()
700                     .map(|tmp| tmp.as_ptr() as *libc::c_char)
701                     .collect();
702             ptrs.push(ptr::null());
703
704             cb(ptrs.as_ptr() as *c_void)
705         }
706         _ => cb(ptr::null())
707     }
708 }
709
710 #[cfg(windows)]
711 fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: |*mut c_void| -> T) -> T {
712     // On win32 we pass an "environment block" which is not a char**, but
713     // rather a concatenation of null-terminated k=v\0 sequences, with a final
714     // \0 to terminate.
715     match env {
716         Some(env) => {
717             let mut blk = Vec::new();
718
719             for pair in env.iter() {
720                 let kv = format!("{}={}",
721                                  pair.ref0().as_str().unwrap(),
722                                  pair.ref1().as_str().unwrap());
723                 blk.push_all(kv.to_utf16().as_slice());
724                 blk.push(0);
725             }
726
727             blk.push(0);
728
729             cb(blk.as_mut_ptr() as *mut c_void)
730         }
731         _ => cb(ptr::mut_null())
732     }
733 }
734
735 #[cfg(windows)]
736 fn with_dirp<T>(d: Option<&CString>, cb: |*u16| -> T) -> T {
737     match d {
738       Some(dir) => {
739           let dir_str = dir.as_str()
740                            .expect("expected workingdirectory to be utf-8 encoded");
741           let dir_str = dir_str.to_utf16().append_one(0);
742           cb(dir_str.as_ptr())
743       },
744       None => cb(ptr::null())
745     }
746 }
747
748 #[cfg(windows)]
749 fn free_handle(handle: *()) {
750     assert!(unsafe {
751         libc::CloseHandle(mem::transmute(handle)) != 0
752     })
753 }
754
755 #[cfg(unix)]
756 fn free_handle(_handle: *()) {
757     // unix has no process handle object, just a pid
758 }
759
760 #[cfg(unix)]
761 fn translate_status(status: c_int) -> rtio::ProcessExit {
762     #![allow(non_snake_case_functions)]
763     #[cfg(target_os = "linux")]
764     #[cfg(target_os = "android")]
765     mod imp {
766         pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
767         pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
768         pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
769     }
770
771     #[cfg(target_os = "macos")]
772     #[cfg(target_os = "ios")]
773     #[cfg(target_os = "freebsd")]
774     mod imp {
775         pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 }
776         pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 }
777         pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 }
778     }
779
780     if imp::WIFEXITED(status) {
781         rtio::ExitStatus(imp::WEXITSTATUS(status) as int)
782     } else {
783         rtio::ExitSignal(imp::WTERMSIG(status) as int)
784     }
785 }
786
787 /**
788  * Waits for a process to exit and returns the exit code, failing
789  * if there is no process with the specified id.
790  *
791  * Note that this is private to avoid race conditions on unix where if
792  * a user calls waitpid(some_process.get_id()) then some_process.finish()
793  * and some_process.destroy() and some_process.finalize() will then either
794  * operate on a none-existent process or, even worse, on a newer process
795  * with the same id.
796  */
797 #[cfg(windows)]
798 fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
799     use libc::types::os::arch::extra::DWORD;
800     use libc::consts::os::extra::{
801         SYNCHRONIZE,
802         PROCESS_QUERY_INFORMATION,
803         FALSE,
804         STILL_ACTIVE,
805         INFINITE,
806         WAIT_TIMEOUT,
807         WAIT_OBJECT_0,
808     };
809     use libc::funcs::extra::kernel32::{
810         OpenProcess,
811         GetExitCodeProcess,
812         CloseHandle,
813         WaitForSingleObject,
814     };
815
816     unsafe {
817         let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
818                                   FALSE,
819                                   pid as DWORD);
820         if process.is_null() {
821             return Err(super::last_error())
822         }
823
824         loop {
825             let mut status = 0;
826             if GetExitCodeProcess(process, &mut status) == FALSE {
827                 let err = Err(super::last_error());
828                 assert!(CloseHandle(process) != 0);
829                 return err;
830             }
831             if status != STILL_ACTIVE {
832                 assert!(CloseHandle(process) != 0);
833                 return Ok(rtio::ExitStatus(status as int));
834             }
835             let interval = if deadline == 0 {
836                 INFINITE
837             } else {
838                 let now = ::io::timer::now();
839                 if deadline < now {0} else {(deadline - now) as u32}
840             };
841             match WaitForSingleObject(process, interval) {
842                 WAIT_OBJECT_0 => {}
843                 WAIT_TIMEOUT => {
844                     assert!(CloseHandle(process) != 0);
845                     return Err(util::timeout("process wait timed out"))
846                 }
847                 _ => {
848                     let err = Err(super::last_error());
849                     assert!(CloseHandle(process) != 0);
850                     return err
851                 }
852             }
853         }
854     }
855 }
856
857 #[cfg(unix)]
858 fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
859     use std::cmp;
860     use std::comm;
861
862     static mut WRITE_FD: libc::c_int = 0;
863
864     let mut status = 0 as c_int;
865     if deadline == 0 {
866         return match retry(|| unsafe { c::waitpid(pid, &mut status, 0) }) {
867             -1 => fail!("unknown waitpid error: {}", super::last_error().code),
868             _ => Ok(translate_status(status)),
869         }
870     }
871
872     // On unix, wait() and its friends have no timeout parameters, so there is
873     // no way to time out a thread in wait(). From some googling and some
874     // thinking, it appears that there are a few ways to handle timeouts in
875     // wait(), but the only real reasonable one for a multi-threaded program is
876     // to listen for SIGCHLD.
877     //
878     // With this in mind, the waiting mechanism with a timeout barely uses
879     // waitpid() at all. There are a few times that waitpid() is invoked with
880     // WNOHANG, but otherwise all the necessary blocking is done by waiting for
881     // a SIGCHLD to arrive (and that blocking has a timeout). Note, however,
882     // that waitpid() is still used to actually reap the child.
883     //
884     // Signal handling is super tricky in general, and this is no exception. Due
885     // to the async nature of SIGCHLD, we use the self-pipe trick to transmit
886     // data out of the signal handler to the rest of the application. The first
887     // idea would be to have each thread waiting with a timeout to read this
888     // output file descriptor, but a write() is akin to a signal(), not a
889     // broadcast(), so it would only wake up one thread, and possibly the wrong
890     // thread. Hence a helper thread is used.
891     //
892     // The helper thread here is responsible for farming requests for a
893     // waitpid() with a timeout, and then processing all of the wait requests.
894     // By guaranteeing that only this helper thread is reading half of the
895     // self-pipe, we're sure that we'll never lose a SIGCHLD. This helper thread
896     // is also responsible for select() to wait for incoming messages or
897     // incoming SIGCHLD messages, along with passing an appropriate timeout to
898     // select() to wake things up as necessary.
899     //
900     // The ordering of the following statements is also very purposeful. First,
901     // we must be guaranteed that the helper thread is booted and available to
902     // receive SIGCHLD signals, and then we must also ensure that we do a
903     // nonblocking waitpid() at least once before we go ask the sigchld helper.
904     // This prevents the race where the child exits, we boot the helper, and
905     // then we ask for the child's exit status (never seeing a sigchld).
906     //
907     // The actual communication between the helper thread and this thread is
908     // quite simple, just a channel moving data around.
909
910     unsafe { HELPER.boot(register_sigchld, waitpid_helper) }
911
912     match waitpid_nowait(pid) {
913         Some(ret) => return Ok(ret),
914         None => {}
915     }
916
917     let (tx, rx) = channel();
918     unsafe { HELPER.send(NewChild(pid, tx, deadline)); }
919     return match rx.recv_opt() {
920         Ok(e) => Ok(e),
921         Err(()) => Err(util::timeout("wait timed out")),
922     };
923
924     // Register a new SIGCHLD handler, returning the reading half of the
925     // self-pipe plus the old handler registered (return value of sigaction).
926     //
927     // Be sure to set up the self-pipe first because as soon as we register a
928     // handler we're going to start receiving signals.
929     fn register_sigchld() -> (libc::c_int, c::sigaction) {
930         unsafe {
931             let mut pipes = [0, ..2];
932             assert_eq!(libc::pipe(pipes.as_mut_ptr()), 0);
933             util::set_nonblocking(pipes[0], true).ok().unwrap();
934             util::set_nonblocking(pipes[1], true).ok().unwrap();
935             WRITE_FD = pipes[1];
936
937             let mut old: c::sigaction = mem::zeroed();
938             let mut new: c::sigaction = mem::zeroed();
939             new.sa_handler = sigchld_handler;
940             new.sa_flags = c::SA_NOCLDSTOP;
941             assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0);
942             (pipes[0], old)
943         }
944     }
945
946     // Helper thread for processing SIGCHLD messages
947     fn waitpid_helper(input: libc::c_int,
948                       messages: Receiver<Req>,
949                       (read_fd, old): (libc::c_int, c::sigaction)) {
950         util::set_nonblocking(input, true).ok().unwrap();
951         let mut set: c::fd_set = unsafe { mem::zeroed() };
952         let mut tv: libc::timeval;
953         let mut active = Vec::<(libc::pid_t, Sender<rtio::ProcessExit>, u64)>::new();
954         let max = cmp::max(input, read_fd) + 1;
955
956         'outer: loop {
957             // Figure out the timeout of our syscall-to-happen. If we're waiting
958             // for some processes, then they'll have a timeout, otherwise we
959             // wait indefinitely for a message to arrive.
960             //
961             // FIXME: sure would be nice to not have to scan the entire array
962             let min = active.iter().map(|a| *a.ref2()).enumerate().min_by(|p| {
963                 p.val1()
964             });
965             let (p, idx) = match min {
966                 Some((idx, deadline)) => {
967                     let now = ::io::timer::now();
968                     let ms = if now < deadline {deadline - now} else {0};
969                     tv = util::ms_to_timeval(ms);
970                     (&tv as *_, idx)
971                 }
972                 None => (ptr::null(), -1),
973             };
974
975             // Wait for something to happen
976             c::fd_set(&mut set, input);
977             c::fd_set(&mut set, read_fd);
978             match unsafe { c::select(max, &set, ptr::null(), ptr::null(), p) } {
979                 // interrupted, retry
980                 -1 if os::errno() == libc::EINTR as int => continue,
981
982                 // We read something, break out and process
983                 1 | 2 => {}
984
985                 // Timeout, the pending request is removed
986                 0 => {
987                     drop(active.remove(idx));
988                     continue
989                 }
990
991                 n => fail!("error in select {} ({})", os::errno(), n),
992             }
993
994             // Process any pending messages
995             if drain(input) {
996                 loop {
997                     match messages.try_recv() {
998                         Ok(NewChild(pid, tx, deadline)) => {
999                             active.push((pid, tx, deadline));
1000                         }
1001                         Err(comm::Disconnected) => {
1002                             assert!(active.len() == 0);
1003                             break 'outer;
1004                         }
1005                         Err(comm::Empty) => break,
1006                     }
1007                 }
1008             }
1009
1010             // If a child exited (somehow received SIGCHLD), then poll all
1011             // children to see if any of them exited.
1012             //
1013             // We also attempt to be responsible netizens when dealing with
1014             // SIGCHLD by invoking any previous SIGCHLD handler instead of just
1015             // ignoring any previous SIGCHLD handler. Note that we don't provide
1016             // a 1:1 mapping of our handler invocations to the previous handler
1017             // invocations because we drain the `read_fd` entirely. This is
1018             // probably OK because the kernel is already allowed to coalesce
1019             // simultaneous signals, we're just doing some extra coalescing.
1020             //
1021             // Another point of note is that this likely runs the signal handler
1022             // on a different thread than the one that received the signal. I
1023             // *think* this is ok at this time.
1024             //
1025             // The main reason for doing this is to allow stdtest to run native
1026             // tests as well. Both libgreen and libnative are running around
1027             // with process timeouts, but libgreen should get there first
1028             // (currently libuv doesn't handle old signal handlers).
1029             if drain(read_fd) {
1030                 let i: uint = unsafe { mem::transmute(old.sa_handler) };
1031                 if i != 0 {
1032                     assert!(old.sa_flags & c::SA_SIGINFO == 0);
1033                     (old.sa_handler)(c::SIGCHLD);
1034                 }
1035
1036                 // FIXME: sure would be nice to not have to scan the entire
1037                 //        array...
1038                 active.retain(|&(pid, ref tx, _)| {
1039                     match waitpid_nowait(pid) {
1040                         Some(msg) => { tx.send(msg); false }
1041                         None => true,
1042                     }
1043                 });
1044             }
1045         }
1046
1047         // Once this helper thread is done, we re-register the old sigchld
1048         // handler and close our intermediate file descriptors.
1049         unsafe {
1050             assert_eq!(c::sigaction(c::SIGCHLD, &old, ptr::mut_null()), 0);
1051             let _ = libc::close(read_fd);
1052             let _ = libc::close(WRITE_FD);
1053             WRITE_FD = -1;
1054         }
1055     }
1056
1057     // Drain all pending data from the file descriptor, returning if any data
1058     // could be drained. This requires that the file descriptor is in
1059     // nonblocking mode.
1060     fn drain(fd: libc::c_int) -> bool {
1061         let mut ret = false;
1062         loop {
1063             let mut buf = [0u8, ..1];
1064             match unsafe {
1065                 libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void,
1066                            buf.len() as libc::size_t)
1067             } {
1068                 n if n > 0 => { ret = true; }
1069                 0 => return true,
1070                 -1 if util::wouldblock() => return ret,
1071                 n => fail!("bad read {} ({})", os::last_os_error(), n),
1072             }
1073         }
1074     }
1075
1076     // Signal handler for SIGCHLD signals, must be async-signal-safe!
1077     //
1078     // This function will write to the writing half of the "self pipe" to wake
1079     // up the helper thread if it's waiting. Note that this write must be
1080     // nonblocking because if it blocks and the reader is the thread we
1081     // interrupted, then we'll deadlock.
1082     //
1083     // When writing, if the write returns EWOULDBLOCK then we choose to ignore
1084     // it. At that point we're guaranteed that there's something in the pipe
1085     // which will wake up the other end at some point, so we just allow this
1086     // signal to be coalesced with the pending signals on the pipe.
1087     extern fn sigchld_handler(_signum: libc::c_int) {
1088         let mut msg = 1;
1089         match unsafe {
1090             libc::write(WRITE_FD, &mut msg as *mut _ as *libc::c_void, 1)
1091         } {
1092             1 => {}
1093             -1 if util::wouldblock() => {} // see above comments
1094             n => fail!("bad error on write fd: {} {}", n, os::errno()),
1095         }
1096     }
1097 }
1098
1099 fn waitpid_nowait(pid: pid_t) -> Option<rtio::ProcessExit> {
1100     return waitpid_os(pid);
1101
1102     // This code path isn't necessary on windows
1103     #[cfg(windows)]
1104     fn waitpid_os(_pid: pid_t) -> Option<rtio::ProcessExit> { None }
1105
1106     #[cfg(unix)]
1107     fn waitpid_os(pid: pid_t) -> Option<rtio::ProcessExit> {
1108         let mut status = 0 as c_int;
1109         match retry(|| unsafe {
1110             c::waitpid(pid, &mut status, c::WNOHANG)
1111         }) {
1112             n if n == pid => Some(translate_status(status)),
1113             0 => None,
1114             n => fail!("unknown waitpid error `{}`: {}", n,
1115                        super::last_error().code),
1116         }
1117     }
1118 }
1119
1120 #[cfg(test)]
1121 mod tests {
1122
1123     #[test] #[cfg(windows)]
1124     fn test_make_command_line() {
1125         use std::str;
1126         use std::c_str::CString;
1127         use super::make_command_line;
1128
1129         fn test_wrapper(prog: &str, args: &[&str]) -> String {
1130             make_command_line(&prog.to_c_str(),
1131                               args.iter()
1132                                   .map(|a| a.to_c_str())
1133                                   .collect::<Vec<CString>>()
1134                                   .as_slice())
1135         }
1136
1137         assert_eq!(
1138             test_wrapper("prog", ["aaa", "bbb", "ccc"]),
1139             "prog aaa bbb ccc".to_string()
1140         );
1141
1142         assert_eq!(
1143             test_wrapper("C:\\Program Files\\blah\\blah.exe", ["aaa"]),
1144             "\"C:\\Program Files\\blah\\blah.exe\" aaa".to_string()
1145         );
1146         assert_eq!(
1147             test_wrapper("C:\\Program Files\\test", ["aa\"bb"]),
1148             "\"C:\\Program Files\\test\" aa\\\"bb".to_string()
1149         );
1150         assert_eq!(
1151             test_wrapper("echo", ["a b c"]),
1152             "echo \"a b c\"".to_string()
1153         );
1154         assert_eq!(
1155             test_wrapper("\u03c0\u042f\u97f3\u00e6\u221e", []),
1156             "\u03c0\u042f\u97f3\u00e6\u221e".to_string()
1157         );
1158     }
1159 }