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