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