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