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.
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.
11 use io::{self, Error, ErrorKind};
12 use libc::{self, c_int, gid_t, pid_t, uid_t};
17 use sys::process::process_common::*;
19 ////////////////////////////////////////////////////////////////////////////////
21 ////////////////////////////////////////////////////////////////////////////////
24 pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
25 -> io::Result<(Process, StdioPipes)> {
28 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
31 return Err(io::Error::new(ErrorKind::InvalidInput,
32 "nul byte found in provided data"));
35 let (ours, theirs) = self.setup_io(default, needs_stdin)?;
36 let (input, output) = sys::pipe::anon_pipe()?;
39 match cvt(libc::fork())? {
42 let err = self.do_exec(theirs);
43 let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
49 CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
50 CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
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());
62 let mut p = Process { pid: pid, status: None };
64 let mut bytes = [0; 8];
66 // loop to handle EINTR
68 match input.read(&mut bytes) {
69 Ok(0) => return Ok((p, ours)),
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))
78 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
80 assert!(p.wait().is_ok(),
81 "wait() should either return Ok or panic");
82 panic!("the CLOEXEC pipe failed: {:?}", e)
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")
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;
98 ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
102 pub fn exec(&mut self, default: Stdio) -> io::Error {
104 return io::Error::new(ErrorKind::InvalidInput,
105 "nul byte found in provided data")
108 match self.setup_io(default, true) {
109 Ok((_, theirs)) => unsafe { self.do_exec(theirs) },
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
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.
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.
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.
136 // For this reason, the block of code below should contain 0
137 // invocations of either malloc of free (or their related friends).
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};
148 ($e:expr) => (match $e {
154 if let Some(fd) = stdio.stdin.fd() {
155 t!(cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO)));
157 if let Some(fd) = stdio.stdout.fd() {
158 t!(cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO)));
160 if let Some(fd) = stdio.stderr.fd() {
161 t!(cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO)));
164 if let Some(u) = self.get_gid() {
165 t!(cvt(libc::setgid(u as gid_t)));
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());
177 t!(cvt(libc::setuid(u as uid_t)));
179 if let Some(ref cwd) = *self.get_cwd() {
180 t!(cvt(libc::chdir(cwd.as_ptr())));
182 if let Some(ref envp) = *self.get_envp() {
183 *sys::os::environ() = envp.as_ptr();
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,
199 let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
200 if ret == libc::SIG_ERR {
201 return io::Error::last_os_error()
205 for callback in self.get_closures().iter_mut() {
209 libc::execvp(self.get_argv()[0], self.get_argv().as_ptr());
210 io::Error::last_os_error()
214 ////////////////////////////////////////////////////////////////////////////////
216 ////////////////////////////////////////////////////////////////////////////////
218 /// The unique id of the process (this should never be negative).
221 status: Option<ExitStatus>,
225 pub fn id(&self) -> u32 {
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"))
237 cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ())
240 pub fn wait(&mut self) -> io::Result<ExitStatus> {
242 if let Some(status) = self.status {
245 let mut status = 0 as c_int;
246 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
247 self.status = Some(ExitStatus::new(status));
248 Ok(ExitStatus::new(status))