]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process.rs
Auto merge of #21959 - dhuseby:bitrig-support, r=brson
[rust.git] / src / libstd / sys / unix / process.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12 use self::Req::*;
13
14 use collections::HashMap;
15 #[cfg(stage0)]
16 use collections::hash_map::Hasher;
17 use ffi::CString;
18 use hash::Hash;
19 use old_io::process::{ProcessExit, ExitStatus, ExitSignal};
20 use old_io::{self, IoResult, IoError, EndOfFile};
21 use libc::{self, pid_t, c_void, c_int};
22 use mem;
23 use os;
24 use old_path::BytesContainer;
25 use ptr;
26 use sync::mpsc::{channel, Sender, Receiver};
27 use sys::fs::FileDesc;
28 use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval};
29 use sys_common::helper_thread::Helper;
30 use sys_common::{AsInner, mkerr_libc, timeout};
31
32 pub use sys_common::ProcessConfig;
33
34 helper_init! { static HELPER: Helper<Req> }
35
36 /// Unix-specific extensions to the Command builder
37 pub struct CommandExt {
38     uid: Option<u32>,
39     gid: Option<u32>,
40 }
41
42 /// The unique id of the process (this should never be negative).
43 pub struct Process {
44     pub pid: pid_t
45 }
46
47 enum Req {
48     NewChild(libc::pid_t, Sender<ProcessExit>, u64),
49 }
50
51 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
52
53 impl Process {
54     pub fn id(&self) -> pid_t {
55         self.pid
56     }
57
58     pub unsafe fn kill(&self, signal: int) -> IoResult<()> {
59         Process::killpid(self.pid, signal)
60     }
61
62     pub unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
63         let r = libc::funcs::posix88::signal::kill(pid, signal as c_int);
64         mkerr_libc(r)
65     }
66
67     #[cfg(stage0)]
68     pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
69                               out_fd: Option<P>, err_fd: Option<P>)
70                               -> IoResult<Process>
71         where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
72               K: BytesContainer + Eq + Hash<Hasher>, V: BytesContainer
73     {
74         use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
75
76         mod rustrt {
77             extern {
78                 pub fn rust_unset_sigprocmask();
79             }
80         }
81
82         #[cfg(all(target_os = "android", target_arch = "aarch64"))]
83         unsafe fn getdtablesize() -> c_int {
84             libc::sysconf(libc::consts::os::sysconf::_SC_OPEN_MAX) as c_int
85         }
86         #[cfg(not(all(target_os = "android", target_arch = "aarch64")))]
87         unsafe fn getdtablesize() -> c_int {
88             libc::funcs::bsd44::getdtablesize()
89         }
90
91         unsafe fn set_cloexec(fd: c_int) {
92             let ret = c::ioctl(fd, c::FIOCLEX);
93             assert_eq!(ret, 0);
94         }
95
96         let dirp = cfg.cwd().map(|c| c.as_ptr()).unwrap_or(ptr::null());
97
98         // temporary until unboxed closures land
99         let cfg = unsafe {
100             mem::transmute::<&ProcessConfig<K,V>,&'static ProcessConfig<K,V>>(cfg)
101         };
102
103         with_envp(cfg.env(), move|envp: *const c_void| {
104             with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe {
105                 let (input, mut output) = try!(sys::os::pipe());
106
107                 // We may use this in the child, so perform allocations before the
108                 // fork
109                 let devnull = b"/dev/null\0";
110
111                 set_cloexec(output.fd());
112
113                 let pid = fork();
114                 if pid < 0 {
115                     return Err(super::last_error())
116                 } else if pid > 0 {
117                     #[inline]
118                     fn combine(arr: &[u8]) -> i32 {
119                         let a = arr[0] as u32;
120                         let b = arr[1] as u32;
121                         let c = arr[2] as u32;
122                         let d = arr[3] as u32;
123
124                         ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
125                     }
126
127                     let p = Process{ pid: pid };
128                     drop(output);
129                     let mut bytes = [0; 8];
130                     return match input.read(&mut bytes) {
131                         Ok(8) => {
132                             assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
133                                 "Validation on the CLOEXEC pipe failed: {:?}", bytes);
134                             let errno = combine(&bytes[0.. 4]);
135                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
136                             Err(super::decode_error(errno))
137                         }
138                         Err(ref e) if e.kind == EndOfFile => Ok(p),
139                         Err(e) => {
140                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
141                             panic!("the CLOEXEC pipe failed: {:?}", e)
142                         },
143                         Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
144                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
145                             panic!("short read on the CLOEXEC pipe")
146                         }
147                     };
148                 }
149
150                 // And at this point we've reached a special time in the life of the
151                 // child. The child must now be considered hamstrung and unable to
152                 // do anything other than syscalls really. Consider the following
153                 // scenario:
154                 //
155                 //      1. Thread A of process 1 grabs the malloc() mutex
156                 //      2. Thread B of process 1 forks(), creating thread C
157                 //      3. Thread C of process 2 then attempts to malloc()
158                 //      4. The memory of process 2 is the same as the memory of
159                 //         process 1, so the mutex is locked.
160                 //
161                 // This situation looks a lot like deadlock, right? It turns out
162                 // that this is what pthread_atfork() takes care of, which is
163                 // presumably implemented across platforms. The first thing that
164                 // threads to *before* forking is to do things like grab the malloc
165                 // mutex, and then after the fork they unlock it.
166                 //
167                 // Despite this information, libnative's spawn has been witnessed to
168                 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
169                 // all collected backtraces point at malloc/free traffic in the
170                 // child spawned process.
171                 //
172                 // For this reason, the block of code below should contain 0
173                 // invocations of either malloc of free (or their related friends).
174                 //
175                 // As an example of not having malloc/free traffic, we don't close
176                 // this file descriptor by dropping the FileDesc (which contains an
177                 // allocation). Instead we just close it manually. This will never
178                 // have the drop glue anyway because this code never returns (the
179                 // child will either exec() or invoke libc::exit)
180                 let _ = libc::close(input.fd());
181
182                 fn fail(output: &mut FileDesc) -> ! {
183                     let errno = sys::os::errno() as u32;
184                     let bytes = [
185                         (errno >> 24) as u8,
186                         (errno >> 16) as u8,
187                         (errno >>  8) as u8,
188                         (errno >>  0) as u8,
189                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
190                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
191                     ];
192                     // pipe I/O up to PIPE_BUF bytes should be atomic
193                     assert!(output.write(&bytes).is_ok());
194                     unsafe { libc::_exit(1) }
195                 }
196
197                 rustrt::rust_unset_sigprocmask();
198
199                 // If a stdio file descriptor is set to be ignored (via a -1 file
200                 // descriptor), then we don't actually close it, but rather open
201                 // up /dev/null into that file descriptor. Otherwise, the first file
202                 // descriptor opened up in the child would be numbered as one of the
203                 // stdio file descriptors, which is likely to wreak havoc.
204                 let setup = |src: Option<P>, dst: c_int| {
205                     let src = match src {
206                         None => {
207                             let flags = if dst == libc::STDIN_FILENO {
208                                 libc::O_RDONLY
209                             } else {
210                                 libc::O_RDWR
211                             };
212                             libc::open(devnull.as_ptr() as *const _, flags, 0)
213                         }
214                         Some(obj) => {
215                             let fd = obj.as_inner().fd();
216                             // Leak the memory and the file descriptor. We're in the
217                             // child now an all our resources are going to be
218                             // cleaned up very soon
219                             mem::forget(obj);
220                             fd
221                         }
222                     };
223                     src != -1 && retry(|| dup2(src, dst)) != -1
224                 };
225
226                 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
227                 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
228                 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
229
230                 // close all other fds
231                 for fd in (3..getdtablesize()).rev() {
232                     if fd != output.fd() {
233                         let _ = close(fd as c_int);
234                     }
235                 }
236
237                 match cfg.gid() {
238                     Some(u) => {
239                         if libc::setgid(u as libc::gid_t) != 0 {
240                             fail(&mut output);
241                         }
242                     }
243                     None => {}
244                 }
245                 match cfg.uid() {
246                     Some(u) => {
247                         // When dropping privileges from root, the `setgroups` call
248                         // will remove any extraneous groups. If we don't call this,
249                         // then even though our uid has dropped, we may still have
250                         // groups that enable us to do super-user things. This will
251                         // fail if we aren't root, so don't bother checking the
252                         // return value, this is just done as an optimistic
253                         // privilege dropping function.
254                         extern {
255                             fn setgroups(ngroups: libc::c_int,
256                                          ptr: *const libc::c_void) -> libc::c_int;
257                         }
258                         let _ = setgroups(0, ptr::null());
259
260                         if libc::setuid(u as libc::uid_t) != 0 {
261                             fail(&mut output);
262                         }
263                     }
264                     None => {}
265                 }
266                 if cfg.detach() {
267                     // Don't check the error of setsid because it fails if we're the
268                     // process leader already. We just forked so it shouldn't return
269                     // error, but ignore it anyway.
270                     let _ = libc::setsid();
271                 }
272                 if !dirp.is_null() && chdir(dirp) == -1 {
273                     fail(&mut output);
274                 }
275                 if !envp.is_null() {
276                     *sys::os::environ() = envp as *const _;
277                 }
278                 let _ = execvp(*argv, argv as *mut _);
279                 fail(&mut output);
280             })
281         })
282     }
283     #[cfg(not(stage0))]
284     pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
285                               out_fd: Option<P>, err_fd: Option<P>)
286                               -> IoResult<Process>
287         where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
288               K: BytesContainer + Eq + Hash, V: BytesContainer
289     {
290         use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
291         use libc::funcs::bsd44::getdtablesize;
292
293         mod rustrt {
294             extern {
295                 pub fn rust_unset_sigprocmask();
296             }
297         }
298
299         unsafe fn set_cloexec(fd: c_int) {
300             let ret = c::ioctl(fd, c::FIOCLEX);
301             assert_eq!(ret, 0);
302         }
303
304         let dirp = cfg.cwd().map(|c| c.as_ptr()).unwrap_or(ptr::null());
305
306         // temporary until unboxed closures land
307         let cfg = unsafe {
308             mem::transmute::<&ProcessConfig<K,V>,&'static ProcessConfig<K,V>>(cfg)
309         };
310
311         with_envp(cfg.env(), move|envp: *const c_void| {
312             with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe {
313                 let (input, mut output) = try!(sys::os::pipe());
314
315                 // We may use this in the child, so perform allocations before the
316                 // fork
317                 let devnull = b"/dev/null\0";
318
319                 set_cloexec(output.fd());
320
321                 let pid = fork();
322                 if pid < 0 {
323                     return Err(super::last_error())
324                 } else if pid > 0 {
325                     #[inline]
326                     fn combine(arr: &[u8]) -> i32 {
327                         let a = arr[0] as u32;
328                         let b = arr[1] as u32;
329                         let c = arr[2] as u32;
330                         let d = arr[3] as u32;
331
332                         ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
333                     }
334
335                     let p = Process{ pid: pid };
336                     drop(output);
337                     let mut bytes = [0; 8];
338                     return match input.read(&mut bytes) {
339                         Ok(8) => {
340                             assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
341                                 "Validation on the CLOEXEC pipe failed: {:?}", bytes);
342                             let errno = combine(&bytes[0.. 4]);
343                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
344                             Err(super::decode_error(errno))
345                         }
346                         Err(ref e) if e.kind == EndOfFile => Ok(p),
347                         Err(e) => {
348                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
349                             panic!("the CLOEXEC pipe failed: {:?}", e)
350                         },
351                         Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
352                             assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic");
353                             panic!("short read on the CLOEXEC pipe")
354                         }
355                     };
356                 }
357
358                 // And at this point we've reached a special time in the life of the
359                 // child. The child must now be considered hamstrung and unable to
360                 // do anything other than syscalls really. Consider the following
361                 // scenario:
362                 //
363                 //      1. Thread A of process 1 grabs the malloc() mutex
364                 //      2. Thread B of process 1 forks(), creating thread C
365                 //      3. Thread C of process 2 then attempts to malloc()
366                 //      4. The memory of process 2 is the same as the memory of
367                 //         process 1, so the mutex is locked.
368                 //
369                 // This situation looks a lot like deadlock, right? It turns out
370                 // that this is what pthread_atfork() takes care of, which is
371                 // presumably implemented across platforms. The first thing that
372                 // threads to *before* forking is to do things like grab the malloc
373                 // mutex, and then after the fork they unlock it.
374                 //
375                 // Despite this information, libnative's spawn has been witnessed to
376                 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
377                 // all collected backtraces point at malloc/free traffic in the
378                 // child spawned process.
379                 //
380                 // For this reason, the block of code below should contain 0
381                 // invocations of either malloc of free (or their related friends).
382                 //
383                 // As an example of not having malloc/free traffic, we don't close
384                 // this file descriptor by dropping the FileDesc (which contains an
385                 // allocation). Instead we just close it manually. This will never
386                 // have the drop glue anyway because this code never returns (the
387                 // child will either exec() or invoke libc::exit)
388                 let _ = libc::close(input.fd());
389
390                 fn fail(output: &mut FileDesc) -> ! {
391                     let errno = sys::os::errno() as u32;
392                     let bytes = [
393                         (errno >> 24) as u8,
394                         (errno >> 16) as u8,
395                         (errno >>  8) as u8,
396                         (errno >>  0) as u8,
397                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
398                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
399                     ];
400                     // pipe I/O up to PIPE_BUF bytes should be atomic
401                     assert!(output.write(&bytes).is_ok());
402                     unsafe { libc::_exit(1) }
403                 }
404
405                 rustrt::rust_unset_sigprocmask();
406
407                 // If a stdio file descriptor is set to be ignored (via a -1 file
408                 // descriptor), then we don't actually close it, but rather open
409                 // up /dev/null into that file descriptor. Otherwise, the first file
410                 // descriptor opened up in the child would be numbered as one of the
411                 // stdio file descriptors, which is likely to wreak havoc.
412                 let setup = |src: Option<P>, dst: c_int| {
413                     let src = match src {
414                         None => {
415                             let flags = if dst == libc::STDIN_FILENO {
416                                 libc::O_RDONLY
417                             } else {
418                                 libc::O_RDWR
419                             };
420                             libc::open(devnull.as_ptr() as *const _, flags, 0)
421                         }
422                         Some(obj) => {
423                             let fd = obj.as_inner().fd();
424                             // Leak the memory and the file descriptor. We're in the
425                             // child now an all our resources are going to be
426                             // cleaned up very soon
427                             mem::forget(obj);
428                             fd
429                         }
430                     };
431                     src != -1 && retry(|| dup2(src, dst)) != -1
432                 };
433
434                 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
435                 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
436                 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
437
438                 // close all other fds
439                 for fd in (3..getdtablesize()).rev() {
440                     if fd != output.fd() {
441                         let _ = close(fd as c_int);
442                     }
443                 }
444
445                 match cfg.gid() {
446                     Some(u) => {
447                         if libc::setgid(u as libc::gid_t) != 0 {
448                             fail(&mut output);
449                         }
450                     }
451                     None => {}
452                 }
453                 match cfg.uid() {
454                     Some(u) => {
455                         // When dropping privileges from root, the `setgroups` call
456                         // will remove any extraneous groups. If we don't call this,
457                         // then even though our uid has dropped, we may still have
458                         // groups that enable us to do super-user things. This will
459                         // fail if we aren't root, so don't bother checking the
460                         // return value, this is just done as an optimistic
461                         // privilege dropping function.
462                         extern {
463                             fn setgroups(ngroups: libc::c_int,
464                                          ptr: *const libc::c_void) -> libc::c_int;
465                         }
466                         let _ = setgroups(0, ptr::null());
467
468                         if libc::setuid(u as libc::uid_t) != 0 {
469                             fail(&mut output);
470                         }
471                     }
472                     None => {}
473                 }
474                 if cfg.detach() {
475                     // Don't check the error of setsid because it fails if we're the
476                     // process leader already. We just forked so it shouldn't return
477                     // error, but ignore it anyway.
478                     let _ = libc::setsid();
479                 }
480                 if !dirp.is_null() && chdir(dirp) == -1 {
481                     fail(&mut output);
482                 }
483                 if !envp.is_null() {
484                     *sys::os::environ() = envp as *const _;
485                 }
486                 let _ = execvp(*argv, argv as *mut _);
487                 fail(&mut output);
488             })
489         })
490     }
491
492     pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> {
493         use cmp;
494         use sync::mpsc::TryRecvError;
495
496         static mut WRITE_FD: libc::c_int = 0;
497
498         let mut status = 0 as c_int;
499         if deadline == 0 {
500             return match retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) }) {
501                 -1 => panic!("unknown waitpid error: {:?}", super::last_error()),
502                 _ => Ok(translate_status(status)),
503             }
504         }
505
506         // On unix, wait() and its friends have no timeout parameters, so there is
507         // no way to time out a thread in wait(). From some googling and some
508         // thinking, it appears that there are a few ways to handle timeouts in
509         // wait(), but the only real reasonable one for a multi-threaded program is
510         // to listen for SIGCHLD.
511         //
512         // With this in mind, the waiting mechanism with a timeout barely uses
513         // waitpid() at all. There are a few times that waitpid() is invoked with
514         // WNOHANG, but otherwise all the necessary blocking is done by waiting for
515         // a SIGCHLD to arrive (and that blocking has a timeout). Note, however,
516         // that waitpid() is still used to actually reap the child.
517         //
518         // Signal handling is super tricky in general, and this is no exception. Due
519         // to the async nature of SIGCHLD, we use the self-pipe trick to transmit
520         // data out of the signal handler to the rest of the application. The first
521         // idea would be to have each thread waiting with a timeout to read this
522         // output file descriptor, but a write() is akin to a signal(), not a
523         // broadcast(), so it would only wake up one thread, and possibly the wrong
524         // thread. Hence a helper thread is used.
525         //
526         // The helper thread here is responsible for farming requests for a
527         // waitpid() with a timeout, and then processing all of the wait requests.
528         // By guaranteeing that only this helper thread is reading half of the
529         // self-pipe, we're sure that we'll never lose a SIGCHLD. This helper thread
530         // is also responsible for select() to wait for incoming messages or
531         // incoming SIGCHLD messages, along with passing an appropriate timeout to
532         // select() to wake things up as necessary.
533         //
534         // The ordering of the following statements is also very purposeful. First,
535         // we must be guaranteed that the helper thread is booted and available to
536         // receive SIGCHLD signals, and then we must also ensure that we do a
537         // nonblocking waitpid() at least once before we go ask the sigchld helper.
538         // This prevents the race where the child exits, we boot the helper, and
539         // then we ask for the child's exit status (never seeing a sigchld).
540         //
541         // The actual communication between the helper thread and this thread is
542         // quite simple, just a channel moving data around.
543
544         unsafe { HELPER.boot(register_sigchld, waitpid_helper) }
545
546         match self.try_wait() {
547             Some(ret) => return Ok(ret),
548             None => {}
549         }
550
551         let (tx, rx) = channel();
552         unsafe { HELPER.send(NewChild(self.pid, tx, deadline)); }
553         return match rx.recv() {
554             Ok(e) => Ok(e),
555             Err(..) => Err(timeout("wait timed out")),
556         };
557
558         // Register a new SIGCHLD handler, returning the reading half of the
559         // self-pipe plus the old handler registered (return value of sigaction).
560         //
561         // Be sure to set up the self-pipe first because as soon as we register a
562         // handler we're going to start receiving signals.
563         fn register_sigchld() -> (libc::c_int, c::sigaction) {
564             unsafe {
565                 let mut pipes = [0; 2];
566                 assert_eq!(libc::pipe(pipes.as_mut_ptr()), 0);
567                 set_nonblocking(pipes[0], true).ok().unwrap();
568                 set_nonblocking(pipes[1], true).ok().unwrap();
569                 WRITE_FD = pipes[1];
570
571                 let mut old: c::sigaction = mem::zeroed();
572                 let mut new: c::sigaction = mem::zeroed();
573                 new.sa_handler = sigchld_handler;
574                 new.sa_flags = c::SA_NOCLDSTOP;
575                 assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0);
576                 (pipes[0], old)
577             }
578         }
579
580         // Helper thread for processing SIGCHLD messages
581         fn waitpid_helper(input: libc::c_int,
582                           messages: Receiver<Req>,
583                           (read_fd, old): (libc::c_int, c::sigaction)) {
584             set_nonblocking(input, true).ok().unwrap();
585             let mut set: c::fd_set = unsafe { mem::zeroed() };
586             let mut tv: libc::timeval;
587             let mut active = Vec::<(libc::pid_t, Sender<ProcessExit>, u64)>::new();
588             let max = cmp::max(input, read_fd) + 1;
589
590             'outer: loop {
591                 // Figure out the timeout of our syscall-to-happen. If we're waiting
592                 // for some processes, then they'll have a timeout, otherwise we
593                 // wait indefinitely for a message to arrive.
594                 //
595                 // FIXME: sure would be nice to not have to scan the entire array
596                 let min = active.iter().map(|a| a.2).enumerate().min_by(|p| {
597                     p.1
598                 });
599                 let (p, idx) = match min {
600                     Some((idx, deadline)) => {
601                         let now = sys::timer::now();
602                         let ms = if now < deadline {deadline - now} else {0};
603                         tv = ms_to_timeval(ms);
604                         (&mut tv as *mut _, idx)
605                     }
606                     None => (ptr::null_mut(), -1),
607                 };
608
609                 // Wait for something to happen
610                 c::fd_set(&mut set, input);
611                 c::fd_set(&mut set, read_fd);
612                 match unsafe { c::select(max, &mut set, ptr::null_mut(),
613                                          ptr::null_mut(), p) } {
614                     // interrupted, retry
615                     -1 if os::errno() == libc::EINTR as i32 => continue,
616
617                     // We read something, break out and process
618                     1 | 2 => {}
619
620                     // Timeout, the pending request is removed
621                     0 => {
622                         drop(active.remove(idx));
623                         continue
624                     }
625
626                     n => panic!("error in select {:?} ({:?})", os::errno(), n),
627                 }
628
629                 // Process any pending messages
630                 if drain(input) {
631                     loop {
632                         match messages.try_recv() {
633                             Ok(NewChild(pid, tx, deadline)) => {
634                                 active.push((pid, tx, deadline));
635                             }
636                             Err(TryRecvError::Disconnected) => {
637                                 assert!(active.len() == 0);
638                                 break 'outer;
639                             }
640                             Err(TryRecvError::Empty) => break,
641                         }
642                     }
643                 }
644
645                 // If a child exited (somehow received SIGCHLD), then poll all
646                 // children to see if any of them exited.
647                 //
648                 // We also attempt to be responsible netizens when dealing with
649                 // SIGCHLD by invoking any previous SIGCHLD handler instead of just
650                 // ignoring any previous SIGCHLD handler. Note that we don't provide
651                 // a 1:1 mapping of our handler invocations to the previous handler
652                 // invocations because we drain the `read_fd` entirely. This is
653                 // probably OK because the kernel is already allowed to coalesce
654                 // simultaneous signals, we're just doing some extra coalescing.
655                 //
656                 // Another point of note is that this likely runs the signal handler
657                 // on a different thread than the one that received the signal. I
658                 // *think* this is ok at this time.
659                 //
660                 // The main reason for doing this is to allow stdtest to run native
661                 // tests as well. Both libgreen and libnative are running around
662                 // with process timeouts, but libgreen should get there first
663                 // (currently libuv doesn't handle old signal handlers).
664                 if drain(read_fd) {
665                     let i: uint = unsafe { mem::transmute(old.sa_handler) };
666                     if i != 0 {
667                         assert!(old.sa_flags & c::SA_SIGINFO == 0);
668                         (old.sa_handler)(c::SIGCHLD);
669                     }
670
671                     // FIXME: sure would be nice to not have to scan the entire
672                     //        array...
673                     active.retain(|&(pid, ref tx, _)| {
674                         let pr = Process { pid: pid };
675                         match pr.try_wait() {
676                             Some(msg) => { tx.send(msg).unwrap(); false }
677                             None => true,
678                         }
679                     });
680                 }
681             }
682
683             // Once this helper thread is done, we re-register the old sigchld
684             // handler and close our intermediate file descriptors.
685             unsafe {
686                 assert_eq!(c::sigaction(c::SIGCHLD, &old, ptr::null_mut()), 0);
687                 let _ = libc::close(read_fd);
688                 let _ = libc::close(WRITE_FD);
689                 WRITE_FD = -1;
690             }
691         }
692
693         // Drain all pending data from the file descriptor, returning if any data
694         // could be drained. This requires that the file descriptor is in
695         // nonblocking mode.
696         fn drain(fd: libc::c_int) -> bool {
697             let mut ret = false;
698             loop {
699                 let mut buf = [0u8; 1];
700                 match unsafe {
701                     libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void,
702                                buf.len() as libc::size_t)
703                 } {
704                     n if n > 0 => { ret = true; }
705                     0 => return true,
706                     -1 if wouldblock() => return ret,
707                     n => panic!("bad read {:?} ({:?})", os::last_os_error(), n),
708                 }
709             }
710         }
711
712         // Signal handler for SIGCHLD signals, must be async-signal-safe!
713         //
714         // This function will write to the writing half of the "self pipe" to wake
715         // up the helper thread if it's waiting. Note that this write must be
716         // nonblocking because if it blocks and the reader is the thread we
717         // interrupted, then we'll deadlock.
718         //
719         // When writing, if the write returns EWOULDBLOCK then we choose to ignore
720         // it. At that point we're guaranteed that there's something in the pipe
721         // which will wake up the other end at some point, so we just allow this
722         // signal to be coalesced with the pending signals on the pipe.
723         extern fn sigchld_handler(_signum: libc::c_int) {
724             let msg = 1;
725             match unsafe {
726                 libc::write(WRITE_FD, &msg as *const _ as *const libc::c_void, 1)
727             } {
728                 1 => {}
729                 -1 if wouldblock() => {} // see above comments
730                 n => panic!("bad error on write fd: {:?} {:?}", n, os::errno()),
731             }
732         }
733     }
734
735     pub fn try_wait(&self) -> Option<ProcessExit> {
736         let mut status = 0 as c_int;
737         match retry(|| unsafe {
738             c::waitpid(self.pid, &mut status, c::WNOHANG)
739         }) {
740             n if n == self.pid => Some(translate_status(status)),
741             0 => None,
742             n => panic!("unknown waitpid error `{:?}`: {:?}", n,
743                        super::last_error()),
744         }
745     }
746 }
747
748 fn with_argv<T,F>(prog: &CString, args: &[CString],
749                   cb: F)
750                   -> T
751     where F : FnOnce(*const *const libc::c_char) -> T
752 {
753     let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
754
755     // Convert the CStrings into an array of pointers. Note: the
756     // lifetime of the various CStrings involved is guaranteed to be
757     // larger than the lifetime of our invocation of cb, but this is
758     // technically unsafe as the callback could leak these pointers
759     // out of our scope.
760     ptrs.push(prog.as_ptr());
761     ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
762
763     // Add a terminating null pointer (required by libc).
764     ptrs.push(ptr::null());
765
766     cb(ptrs.as_ptr())
767 }
768
769 #[cfg(stage0)]
770 fn with_envp<K,V,T,F>(env: Option<&HashMap<K, V>>,
771                       cb: F)
772                       -> T
773     where F : FnOnce(*const c_void) -> T,
774           K : BytesContainer + Eq + Hash<Hasher>,
775           V : BytesContainer
776 {
777     // On posixy systems we can pass a char** for envp, which is a
778     // null-terminated array of "k=v\0" strings. Since we must create
779     // these strings locally, yet expose a raw pointer to them, we
780     // create a temporary vector to own the CStrings that outlives the
781     // call to cb.
782     match env {
783         Some(env) => {
784             let mut tmps = Vec::with_capacity(env.len());
785
786             for pair in env {
787                 let mut kv = Vec::new();
788                 kv.push_all(pair.0.container_as_bytes());
789                 kv.push('=' as u8);
790                 kv.push_all(pair.1.container_as_bytes());
791                 kv.push(0); // terminating null
792                 tmps.push(kv);
793             }
794
795             // As with `with_argv`, this is unsafe, since cb could leak the pointers.
796             let mut ptrs: Vec<*const libc::c_char> =
797                 tmps.iter()
798                     .map(|tmp| tmp.as_ptr() as *const libc::c_char)
799                     .collect();
800             ptrs.push(ptr::null());
801
802             cb(ptrs.as_ptr() as *const c_void)
803         }
804         _ => cb(ptr::null())
805     }
806 }
807 #[cfg(not(stage0))]
808 fn with_envp<K,V,T,F>(env: Option<&HashMap<K, V>>,
809                       cb: F)
810                       -> T
811     where F : FnOnce(*const c_void) -> T,
812           K : BytesContainer + Eq + Hash,
813           V : BytesContainer
814 {
815     // On posixy systems we can pass a char** for envp, which is a
816     // null-terminated array of "k=v\0" strings. Since we must create
817     // these strings locally, yet expose a raw pointer to them, we
818     // create a temporary vector to own the CStrings that outlives the
819     // call to cb.
820     match env {
821         Some(env) => {
822             let mut tmps = Vec::with_capacity(env.len());
823
824             for pair in env {
825                 let mut kv = Vec::new();
826                 kv.push_all(pair.0.container_as_bytes());
827                 kv.push('=' as u8);
828                 kv.push_all(pair.1.container_as_bytes());
829                 kv.push(0); // terminating null
830                 tmps.push(kv);
831             }
832
833             // As with `with_argv`, this is unsafe, since cb could leak the pointers.
834             let mut ptrs: Vec<*const libc::c_char> =
835                 tmps.iter()
836                     .map(|tmp| tmp.as_ptr() as *const libc::c_char)
837                     .collect();
838             ptrs.push(ptr::null());
839
840             cb(ptrs.as_ptr() as *const c_void)
841         }
842         _ => cb(ptr::null())
843     }
844 }
845
846 fn translate_status(status: c_int) -> ProcessExit {
847     #![allow(non_snake_case)]
848     #[cfg(any(target_os = "linux", target_os = "android"))]
849     mod imp {
850         pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
851         pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
852         pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
853     }
854
855     #[cfg(any(target_os = "macos",
856               target_os = "ios",
857               target_os = "freebsd",
858               target_os = "dragonfly",
859               target_os = "bitrig",
860               target_os = "openbsd"))]
861     mod imp {
862         pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 }
863         pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 }
864         pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 }
865     }
866
867     if imp::WIFEXITED(status) {
868         ExitStatus(imp::WEXITSTATUS(status) as int)
869     } else {
870         ExitSignal(imp::WTERMSIG(status) as int)
871     }
872 }