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