]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process/process_unix.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / libstd / sys / unix / process / process_unix.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 io::{self, Error, ErrorKind};
12 use libc::{self, c_int, gid_t, pid_t, uid_t};
13 use mem;
14 use ptr;
15
16 use sys::cvt;
17 use sys::process::process_common::*;
18
19 ////////////////////////////////////////////////////////////////////////////////
20 // Command
21 ////////////////////////////////////////////////////////////////////////////////
22
23 impl Command {
24     pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
25                  -> io::Result<(Process, StdioPipes)> {
26         use sys;
27
28         const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
29
30         if self.saw_nul() {
31             return Err(io::Error::new(ErrorKind::InvalidInput,
32                                       "nul byte found in provided data"));
33         }
34
35         let (ours, theirs) = self.setup_io(default, needs_stdin)?;
36         let (input, output) = sys::pipe::anon_pipe()?;
37
38         let pid = unsafe {
39             match cvt(libc::fork())? {
40                 0 => {
41                     drop(input);
42                     let err = self.do_exec(theirs);
43                     let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
44                     let bytes = [
45                         (errno >> 24) as u8,
46                         (errno >> 16) as u8,
47                         (errno >>  8) as u8,
48                         (errno >>  0) as u8,
49                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
50                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
51                     ];
52                     // pipe I/O up to PIPE_BUF bytes should be atomic, and then
53                     // we want to be sure we *don't* run at_exit destructors as
54                     // we're being torn down regardless
55                     assert!(output.write(&bytes).is_ok());
56                     libc::_exit(1)
57                 }
58                 n => n,
59             }
60         };
61
62         let mut p = Process { pid: pid, status: None };
63         drop(output);
64         let mut bytes = [0; 8];
65
66         // loop to handle EINTR
67         loop {
68             match input.read(&mut bytes) {
69                 Ok(0) => return Ok((p, ours)),
70                 Ok(8) => {
71                     assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
72                             "Validation on the CLOEXEC pipe failed: {:?}", bytes);
73                     let errno = combine(&bytes[0.. 4]);
74                     assert!(p.wait().is_ok(),
75                             "wait() should either return Ok or panic");
76                     return Err(Error::from_raw_os_error(errno))
77                 }
78                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
79                 Err(e) => {
80                     assert!(p.wait().is_ok(),
81                             "wait() should either return Ok or panic");
82                     panic!("the CLOEXEC pipe failed: {:?}", e)
83                 },
84                 Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
85                     assert!(p.wait().is_ok(),
86                             "wait() should either return Ok or panic");
87                     panic!("short read on the CLOEXEC pipe")
88                 }
89             }
90         }
91
92         fn combine(arr: &[u8]) -> i32 {
93             let a = arr[0] as u32;
94             let b = arr[1] as u32;
95             let c = arr[2] as u32;
96             let d = arr[3] as u32;
97
98             ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
99         }
100     }
101
102     pub fn exec(&mut self, default: Stdio) -> io::Error {
103         if self.saw_nul() {
104             return io::Error::new(ErrorKind::InvalidInput,
105                                   "nul byte found in provided data")
106         }
107
108         match self.setup_io(default, true) {
109             Ok((_, theirs)) => unsafe { self.do_exec(theirs) },
110             Err(e) => e,
111         }
112     }
113
114     // And at this point we've reached a special time in the life of the
115     // child. The child must now be considered hamstrung and unable to
116     // do anything other than syscalls really. Consider the following
117     // scenario:
118     //
119     //      1. Thread A of process 1 grabs the malloc() mutex
120     //      2. Thread B of process 1 forks(), creating thread C
121     //      3. Thread C of process 2 then attempts to malloc()
122     //      4. The memory of process 2 is the same as the memory of
123     //         process 1, so the mutex is locked.
124     //
125     // This situation looks a lot like deadlock, right? It turns out
126     // that this is what pthread_atfork() takes care of, which is
127     // presumably implemented across platforms. The first thing that
128     // threads to *before* forking is to do things like grab the malloc
129     // mutex, and then after the fork they unlock it.
130     //
131     // Despite this information, libnative's spawn has been witnessed to
132     // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
133     // all collected backtraces point at malloc/free traffic in the
134     // child spawned process.
135     //
136     // For this reason, the block of code below should contain 0
137     // invocations of either malloc of free (or their related friends).
138     //
139     // As an example of not having malloc/free traffic, we don't close
140     // this file descriptor by dropping the FileDesc (which contains an
141     // allocation). Instead we just close it manually. This will never
142     // have the drop glue anyway because this code never returns (the
143     // child will either exec() or invoke libc::exit)
144     unsafe fn do_exec(&mut self, stdio: ChildPipes) -> io::Error {
145         use sys::{self, cvt_r};
146
147         macro_rules! t {
148             ($e:expr) => (match $e {
149                 Ok(e) => e,
150                 Err(e) => return e,
151             })
152         }
153
154         if let Some(fd) = stdio.stdin.fd() {
155             t!(cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO)));
156         }
157         if let Some(fd) = stdio.stdout.fd() {
158             t!(cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO)));
159         }
160         if let Some(fd) = stdio.stderr.fd() {
161             t!(cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO)));
162         }
163
164         if let Some(u) = self.get_gid() {
165             t!(cvt(libc::setgid(u as gid_t)));
166         }
167         if let Some(u) = self.get_uid() {
168             // When dropping privileges from root, the `setgroups` call
169             // will remove any extraneous groups. If we don't call this,
170             // then even though our uid has dropped, we may still have
171             // groups that enable us to do super-user things. This will
172             // fail if we aren't root, so don't bother checking the
173             // return value, this is just done as an optimistic
174             // privilege dropping function.
175             let _ = libc::setgroups(0, ptr::null());
176
177             t!(cvt(libc::setuid(u as uid_t)));
178         }
179         if let Some(ref cwd) = *self.get_cwd() {
180             t!(cvt(libc::chdir(cwd.as_ptr())));
181         }
182         if let Some(ref envp) = *self.get_envp() {
183             *sys::os::environ() = envp.as_ptr();
184         }
185
186         // NaCl has no signal support.
187         if cfg!(not(any(target_os = "nacl", target_os = "emscripten"))) {
188             // Reset signal handling so the child process starts in a
189             // standardized state. libstd ignores SIGPIPE, and signal-handling
190             // libraries often set a mask. Child processes inherit ignored
191             // signals and the signal mask from their parent, but most
192             // UNIX programs do not reset these things on their own, so we
193             // need to clean things up now to avoid confusing the program
194             // we're about to run.
195             let mut set: libc::sigset_t = mem::uninitialized();
196             t!(cvt(libc::sigemptyset(&mut set)));
197             t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
198                                          ptr::null_mut())));
199             let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
200             if ret == libc::SIG_ERR {
201                 return io::Error::last_os_error()
202             }
203         }
204
205         for callback in self.get_closures().iter_mut() {
206             t!(callback());
207         }
208
209         libc::execvp(self.get_argv()[0], self.get_argv().as_ptr());
210         io::Error::last_os_error()
211     }
212 }
213
214 ////////////////////////////////////////////////////////////////////////////////
215 // Processes
216 ////////////////////////////////////////////////////////////////////////////////
217
218 /// The unique id of the process (this should never be negative).
219 pub struct Process {
220     pid: pid_t,
221     status: Option<ExitStatus>,
222 }
223
224 impl Process {
225     pub fn id(&self) -> u32 {
226         self.pid as u32
227     }
228
229     pub fn kill(&mut self) -> io::Result<()> {
230         // If we've already waited on this process then the pid can be recycled
231         // and used for another process, and we probably shouldn't be killing
232         // random processes, so just return an error.
233         if self.status.is_some() {
234             Err(Error::new(ErrorKind::InvalidInput,
235                            "invalid argument: can't kill an exited process"))
236         } else {
237             cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ())
238         }
239     }
240
241     pub fn wait(&mut self) -> io::Result<ExitStatus> {
242         use sys::cvt_r;
243         if let Some(status) = self.status {
244             return Ok(status)
245         }
246         let mut status = 0 as c_int;
247         cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
248         self.status = Some(ExitStatus::new(status));
249         Ok(ExitStatus::new(status))
250     }
251
252     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
253         if let Some(status) = self.status {
254             return Ok(Some(status))
255         }
256         let mut status = 0 as c_int;
257         let pid = cvt(unsafe {
258             libc::waitpid(self.pid, &mut status, libc::WNOHANG)
259         })?;
260         if pid == 0 {
261             Ok(None)
262         } else {
263             self.status = Some(ExitStatus::new(status));
264             Ok(Some(ExitStatus::new(status)))
265         }
266     }
267 }