]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process2.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / libstd / sys / unix / process2.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
13 use collections::HashMap;
14 use collections::hash_map::Hasher;
15 use env;
16 use ffi::{OsString, OsStr, CString};
17 use fmt;
18 use hash::Hash;
19 use io::{self, Error, ErrorKind};
20 use libc::{self, pid_t, c_void, c_int, gid_t, uid_t};
21 use mem;
22 use old_io;
23 use os;
24 use os::unix::OsStrExt;
25 use ptr;
26 use sync::mpsc::{channel, Sender, Receiver};
27 use sys::pipe2::AnonPipe;
28 use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval, cvt};
29 use sys_common::AsInner;
30
31 ////////////////////////////////////////////////////////////////////////////////
32 // Command
33 ////////////////////////////////////////////////////////////////////////////////
34
35 #[derive(Clone)]
36 pub struct Command {
37     pub program: CString,
38     pub args: Vec<CString>,
39     pub env: Option<HashMap<OsString, OsString>>,
40     pub cwd: Option<CString>,
41     pub uid: Option<uid_t>,
42     pub gid: Option<gid_t>,
43     pub detach: bool, // not currently exposed in std::process
44 }
45
46 impl Command {
47     pub fn new(program: &OsStr) -> Command {
48         Command {
49             program: program.to_cstring(),
50             args: Vec::new(),
51             env: None,
52             cwd: None,
53             uid: None,
54             gid: None,
55             detach: false,
56         }
57     }
58
59     pub fn arg(&mut self, arg: &OsStr) {
60         self.args.push(arg.to_cstring())
61     }
62     pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
63         self.args.extend(args.map(OsStrExt::to_cstring))
64     }
65     fn init_env_map(&mut self) {
66         if self.env.is_none() {
67             self.env = Some(env::vars_os().collect());
68         }
69     }
70     pub fn env(&mut self, key: &OsStr, val: &OsStr) {
71         self.init_env_map();
72         self.env.as_mut().unwrap().insert(key.to_os_string(), val.to_os_string());
73     }
74     pub fn env_remove(&mut self, key: &OsStr) {
75         self.init_env_map();
76         self.env.as_mut().unwrap().remove(&key.to_os_string());
77     }
78     pub fn env_clear(&mut self) {
79         self.env = Some(HashMap::new())
80     }
81     pub fn cwd(&mut self, dir: &OsStr) {
82         self.cwd = Some(dir.to_cstring())
83     }
84 }
85
86 ////////////////////////////////////////////////////////////////////////////////
87 // Processes
88 ////////////////////////////////////////////////////////////////////////////////
89
90 /// Unix exit statuses
91 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
92 pub enum ExitStatus {
93     /// Normal termination with an exit code.
94     Code(i32),
95
96     /// Termination by signal, with the signal number.
97     ///
98     /// Never generated on Windows.
99     Signal(i32),
100 }
101
102 impl ExitStatus {
103     pub fn success(&self) -> bool {
104         *self == ExitStatus::Code(0)
105     }
106     pub fn code(&self) -> Option<i32> {
107         match *self {
108             ExitStatus::Code(c) => Some(c),
109             _ => None
110         }
111     }
112 }
113
114 impl fmt::Display for ExitStatus {
115     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
116         match *self {
117             ExitStatus::Code(code) =>  write!(f, "exit code: {}", code),
118             ExitStatus::Signal(code) =>  write!(f, "signal: {}", code),
119         }
120     }
121 }
122
123 /// The unique id of the process (this should never be negative).
124 pub struct Process {
125     pid: pid_t
126 }
127
128 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
129
130 impl Process {
131     pub fn id(&self) -> pid_t {
132         self.pid
133     }
134
135     pub unsafe fn kill(&self) -> io::Result<()> {
136         try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL)));
137         Ok(())
138     }
139
140     pub fn spawn(cfg: &Command,
141                  in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>)
142                  -> io::Result<Process>
143     {
144         use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
145         use libc::funcs::bsd44::getdtablesize;
146
147         mod rustrt {
148             extern {
149                 pub fn rust_unset_sigprocmask();
150             }
151         }
152
153         unsafe fn set_cloexec(fd: c_int) {
154             let ret = c::ioctl(fd, c::FIOCLEX);
155             assert_eq!(ret, 0);
156         }
157
158         let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
159
160         with_envp(cfg.env.as_ref(), |envp: *const c_void| {
161             with_argv(&cfg.program, &cfg.args, |argv: *const *const libc::c_char| unsafe {
162                 let (input, mut output) = try!(sys::pipe2::anon_pipe());
163
164                 // We may use this in the child, so perform allocations before the
165                 // fork
166                 let devnull = b"/dev/null\0";
167
168                 set_cloexec(output.raw());
169
170                 let pid = fork();
171                 if pid < 0 {
172                     return Err(Error::last_os_error())
173                 } else if pid > 0 {
174                     #[inline]
175                     fn combine(arr: &[u8]) -> i32 {
176                         let a = arr[0] as u32;
177                         let b = arr[1] as u32;
178                         let c = arr[2] as u32;
179                         let d = arr[3] as u32;
180
181                         ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
182                     }
183
184                     let p = Process{ pid: pid };
185                     drop(output);
186                     let mut bytes = [0; 8];
187
188                     // loop to handle EINTER
189                     loop {
190                         match input.read(&mut bytes) {
191                             Ok(8) => {
192                                 assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
193                                         "Validation on the CLOEXEC pipe failed: {:?}", bytes);
194                                 let errno = combine(&bytes[0.. 4]);
195                                 assert!(p.wait().is_ok(),
196                                         "wait() should either return Ok or panic");
197                                 return Err(Error::from_os_error(errno))
198                             }
199                             Ok(0) => return Ok(p),
200                             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
201                             Err(e) => {
202                                 assert!(p.wait().is_ok(),
203                                         "wait() should either return Ok or panic");
204                                 panic!("the CLOEXEC pipe failed: {:?}", e)
205                             },
206                             Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
207                                 assert!(p.wait().is_ok(),
208                                         "wait() should either return Ok or panic");
209                                 panic!("short read on the CLOEXEC pipe")
210                             }
211                         }
212                     }
213                 }
214
215                 // And at this point we've reached a special time in the life of the
216                 // child. The child must now be considered hamstrung and unable to
217                 // do anything other than syscalls really. Consider the following
218                 // scenario:
219                 //
220                 //      1. Thread A of process 1 grabs the malloc() mutex
221                 //      2. Thread B of process 1 forks(), creating thread C
222                 //      3. Thread C of process 2 then attempts to malloc()
223                 //      4. The memory of process 2 is the same as the memory of
224                 //         process 1, so the mutex is locked.
225                 //
226                 // This situation looks a lot like deadlock, right? It turns out
227                 // that this is what pthread_atfork() takes care of, which is
228                 // presumably implemented across platforms. The first thing that
229                 // threads to *before* forking is to do things like grab the malloc
230                 // mutex, and then after the fork they unlock it.
231                 //
232                 // Despite this information, libnative's spawn has been witnessed to
233                 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
234                 // all collected backtraces point at malloc/free traffic in the
235                 // child spawned process.
236                 //
237                 // For this reason, the block of code below should contain 0
238                 // invocations of either malloc of free (or their related friends).
239                 //
240                 // As an example of not having malloc/free traffic, we don't close
241                 // this file descriptor by dropping the FileDesc (which contains an
242                 // allocation). Instead we just close it manually. This will never
243                 // have the drop glue anyway because this code never returns (the
244                 // child will either exec() or invoke libc::exit)
245                 let _ = libc::close(input.raw());
246
247                 fn fail(output: &mut AnonPipe) -> ! {
248                     let errno = sys::os::errno() as u32;
249                     let bytes = [
250                         (errno >> 24) as u8,
251                         (errno >> 16) as u8,
252                         (errno >>  8) as u8,
253                         (errno >>  0) as u8,
254                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
255                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
256                     ];
257                     // pipe I/O up to PIPE_BUF bytes should be atomic
258                     assert!(output.write(&bytes).is_ok());
259                     unsafe { libc::_exit(1) }
260                 }
261
262                 rustrt::rust_unset_sigprocmask();
263
264                 // If a stdio file descriptor is set to be ignored, we don't
265                 // actually close it, but rather open up /dev/null into that
266                 // file descriptor. Otherwise, the first file descriptor opened
267                 // up in the child would be numbered as one of the stdio file
268                 // descriptors, which is likely to wreak havoc.
269                 let setup = |&: src: Option<AnonPipe>, dst: c_int| {
270                     let src = match src {
271                         None => {
272                             let flags = if dst == libc::STDIN_FILENO {
273                                 libc::O_RDONLY
274                             } else {
275                                 libc::O_RDWR
276                             };
277                             libc::open(devnull.as_ptr() as *const _, flags, 0)
278                         }
279                         Some(obj) => {
280                             let fd = obj.raw();
281                             // Leak the memory and the file descriptor. We're in the
282                             // child now an all our resources are going to be
283                             // cleaned up very soon
284                             mem::forget(obj);
285                             fd
286                         }
287                     };
288                     src != -1 && retry(|| dup2(src, dst)) != -1
289                 };
290
291                 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
292                 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
293                 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
294
295                 // close all other fds
296                 for fd in (3..getdtablesize()).rev() {
297                     if fd != output.raw() {
298                         let _ = close(fd as c_int);
299                     }
300                 }
301
302                 match cfg.gid {
303                     Some(u) => {
304                         if libc::setgid(u as libc::gid_t) != 0 {
305                             fail(&mut output);
306                         }
307                     }
308                     None => {}
309                 }
310                 match cfg.uid {
311                     Some(u) => {
312                         // When dropping privileges from root, the `setgroups` call
313                         // will remove any extraneous groups. If we don't call this,
314                         // then even though our uid has dropped, we may still have
315                         // groups that enable us to do super-user things. This will
316                         // fail if we aren't root, so don't bother checking the
317                         // return value, this is just done as an optimistic
318                         // privilege dropping function.
319                         extern {
320                             fn setgroups(ngroups: libc::c_int,
321                                          ptr: *const libc::c_void) -> libc::c_int;
322                         }
323                         let _ = setgroups(0, ptr::null());
324
325                         if libc::setuid(u as libc::uid_t) != 0 {
326                             fail(&mut output);
327                         }
328                     }
329                     None => {}
330                 }
331                 if cfg.detach {
332                     // Don't check the error of setsid because it fails if we're the
333                     // process leader already. We just forked so it shouldn't return
334                     // error, but ignore it anyway.
335                     let _ = libc::setsid();
336                 }
337                 if !dirp.is_null() && chdir(dirp) == -1 {
338                     fail(&mut output);
339                 }
340                 if !envp.is_null() {
341                     *sys::os::environ() = envp as *const _;
342                 }
343                 let _ = execvp(*argv, argv as *mut _);
344                 fail(&mut output);
345             })
346         })
347     }
348
349     pub fn wait(&self) -> io::Result<ExitStatus> {
350         let mut status = 0 as c_int;
351         try!(cvt(retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) })));
352         Ok(translate_status(status))
353     }
354
355     pub fn try_wait(&self) -> Option<ExitStatus> {
356         let mut status = 0 as c_int;
357         match retry(|| unsafe {
358             c::waitpid(self.pid, &mut status, c::WNOHANG)
359         }) {
360             n if n == self.pid => Some(translate_status(status)),
361             0 => None,
362             n => panic!("unknown waitpid error `{:?}`: {:?}", n,
363                        super::last_error()),
364         }
365     }
366 }
367
368 fn with_argv<T,F>(prog: &CString, args: &[CString], cb: F) -> T
369     where F : FnOnce(*const *const libc::c_char) -> T
370 {
371     let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
372
373     // Convert the CStrings into an array of pointers. Note: the
374     // lifetime of the various CStrings involved is guaranteed to be
375     // larger than the lifetime of our invocation of cb, but this is
376     // technically unsafe as the callback could leak these pointers
377     // out of our scope.
378     ptrs.push(prog.as_ptr());
379     ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
380
381     // Add a terminating null pointer (required by libc).
382     ptrs.push(ptr::null());
383
384     cb(ptrs.as_ptr())
385 }
386
387 fn with_envp<T, F>(env: Option<&HashMap<OsString, OsString>>, cb: F) -> T
388     where F : FnOnce(*const c_void) -> T
389 {
390     // On posixy systems we can pass a char** for envp, which is a
391     // null-terminated array of "k=v\0" strings. Since we must create
392     // these strings locally, yet expose a raw pointer to them, we
393     // create a temporary vector to own the CStrings that outlives the
394     // call to cb.
395     match env {
396         Some(env) => {
397             let mut tmps = Vec::with_capacity(env.len());
398
399             for pair in env {
400                 let mut kv = Vec::new();
401                 kv.push_all(pair.0.as_bytes());
402                 kv.push('=' as u8);
403                 kv.push_all(pair.1.as_bytes());
404                 kv.push(0); // terminating null
405                 tmps.push(kv);
406             }
407
408             // As with `with_argv`, this is unsafe, since cb could leak the pointers.
409             let mut ptrs: Vec<*const libc::c_char> =
410                 tmps.iter()
411                     .map(|tmp| tmp.as_ptr() as *const libc::c_char)
412                     .collect();
413             ptrs.push(ptr::null());
414
415             cb(ptrs.as_ptr() as *const c_void)
416         }
417         _ => cb(ptr::null())
418     }
419 }
420
421 fn translate_status(status: c_int) -> ExitStatus {
422     #![allow(non_snake_case)]
423     #[cfg(any(target_os = "linux", target_os = "android"))]
424     mod imp {
425         pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
426         pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
427         pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
428     }
429
430     #[cfg(any(target_os = "macos",
431               target_os = "ios",
432               target_os = "freebsd",
433               target_os = "dragonfly",
434               target_os = "openbsd"))]
435     mod imp {
436         pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 }
437         pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 }
438         pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 }
439     }
440
441     if imp::WIFEXITED(status) {
442         ExitStatus::Code(imp::WEXITSTATUS(status))
443     } else {
444         ExitStatus::Signal(imp::WTERMSIG(status))
445     }
446 }