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.
13 use collections::HashMap;
14 use collections::hash_map::Hasher;
16 use ffi::{OsString, OsStr, CString};
19 use io::{self, Error, ErrorKind};
20 use libc::{self, pid_t, c_void, c_int, gid_t, uid_t};
24 use os::unix::OsStrExt;
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;
31 ////////////////////////////////////////////////////////////////////////////////
33 ////////////////////////////////////////////////////////////////////////////////
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
47 pub fn new(program: &OsStr) -> Command {
49 program: program.to_cstring(),
59 pub fn arg(&mut self, arg: &OsStr) {
60 self.args.push(arg.to_cstring())
62 pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
63 self.args.extend(args.map(OsStrExt::to_cstring))
65 fn init_env_map(&mut self) {
66 if self.env.is_none() {
67 self.env = Some(env::vars_os().collect());
70 pub fn env(&mut self, key: &OsStr, val: &OsStr) {
72 self.env.as_mut().unwrap().insert(key.to_os_string(), val.to_os_string());
74 pub fn env_remove(&mut self, key: &OsStr) {
76 self.env.as_mut().unwrap().remove(&key.to_os_string());
78 pub fn env_clear(&mut self) {
79 self.env = Some(HashMap::new())
81 pub fn cwd(&mut self, dir: &OsStr) {
82 self.cwd = Some(dir.to_cstring())
86 ////////////////////////////////////////////////////////////////////////////////
88 ////////////////////////////////////////////////////////////////////////////////
90 /// Unix exit statuses
91 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
93 /// Normal termination with an exit code.
96 /// Termination by signal, with the signal number.
98 /// Never generated on Windows.
103 pub fn success(&self) -> bool {
104 *self == ExitStatus::Code(0)
106 pub fn code(&self) -> Option<i32> {
108 ExitStatus::Code(c) => Some(c),
114 impl fmt::Display for ExitStatus {
115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117 ExitStatus::Code(code) => write!(f, "exit code: {}", code),
118 ExitStatus::Signal(code) => write!(f, "signal: {}", code),
123 /// The unique id of the process (this should never be negative).
128 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
131 pub fn id(&self) -> pid_t {
135 pub unsafe fn kill(&self) -> io::Result<()> {
136 try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL)));
140 pub fn spawn(cfg: &Command,
141 in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>)
142 -> io::Result<Process>
144 use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
145 use libc::funcs::bsd44::getdtablesize;
149 pub fn rust_unset_sigprocmask();
153 unsafe fn set_cloexec(fd: c_int) {
154 let ret = c::ioctl(fd, c::FIOCLEX);
158 let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
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());
164 // We may use this in the child, so perform allocations before the
166 let devnull = b"/dev/null\0";
168 set_cloexec(output.raw());
172 return Err(Error::last_os_error())
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;
181 ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
184 let p = Process{ pid: pid };
186 let mut bytes = [0; 8];
188 // loop to handle EINTER
190 match input.read(&mut bytes) {
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))
199 Ok(0) => return Ok(p),
200 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
202 assert!(p.wait().is_ok(),
203 "wait() should either return Ok or panic");
204 panic!("the CLOEXEC pipe failed: {:?}", e)
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")
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
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.
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.
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.
237 // For this reason, the block of code below should contain 0
238 // invocations of either malloc of free (or their related friends).
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());
247 fn fail(output: &mut AnonPipe) -> ! {
248 let errno = sys::os::errno() as u32;
254 CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
255 CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
257 // pipe I/O up to PIPE_BUF bytes should be atomic
258 assert!(output.write(&bytes).is_ok());
259 unsafe { libc::_exit(1) }
262 rustrt::rust_unset_sigprocmask();
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 {
272 let flags = if dst == libc::STDIN_FILENO {
277 libc::open(devnull.as_ptr() as *const _, flags, 0)
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
288 src != -1 && retry(|| dup2(src, dst)) != -1
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) }
295 // close all other fds
296 for fd in (3..getdtablesize()).rev() {
297 if fd != output.raw() {
298 let _ = close(fd as c_int);
304 if libc::setgid(u as libc::gid_t) != 0 {
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.
320 fn setgroups(ngroups: libc::c_int,
321 ptr: *const libc::c_void) -> libc::c_int;
323 let _ = setgroups(0, ptr::null());
325 if libc::setuid(u as libc::uid_t) != 0 {
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();
337 if !dirp.is_null() && chdir(dirp) == -1 {
341 *sys::os::environ() = envp as *const _;
343 let _ = execvp(*argv, argv as *mut _);
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))
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)
360 n if n == self.pid => Some(translate_status(status)),
362 n => panic!("unknown waitpid error `{:?}`: {:?}", n,
363 super::last_error()),
368 fn with_argv<T,F>(prog: &CString, args: &[CString], cb: F) -> T
369 where F : FnOnce(*const *const libc::c_char) -> T
371 let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
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
378 ptrs.push(prog.as_ptr());
379 ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
381 // Add a terminating null pointer (required by libc).
382 ptrs.push(ptr::null());
387 fn with_envp<T, F>(env: Option<&HashMap<OsString, OsString>>, cb: F) -> T
388 where F : FnOnce(*const c_void) -> T
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
397 let mut tmps = Vec::with_capacity(env.len());
400 let mut kv = Vec::new();
401 kv.push_all(pair.0.as_bytes());
403 kv.push_all(pair.1.as_bytes());
404 kv.push(0); // terminating null
408 // As with `with_argv`, this is unsafe, since cb could leak the pointers.
409 let mut ptrs: Vec<*const libc::c_char> =
411 .map(|tmp| tmp.as_ptr() as *const libc::c_char)
413 ptrs.push(ptr::null());
415 cb(ptrs.as_ptr() as *const c_void)
421 fn translate_status(status: c_int) -> ExitStatus {
422 #![allow(non_snake_case)]
423 #[cfg(any(target_os = "linux", target_os = "android"))]
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 }
430 #[cfg(any(target_os = "macos",
432 target_os = "freebsd",
433 target_os = "dragonfly",
434 target_os = "openbsd"))]
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 }
441 if imp::WIFEXITED(status) {
442 ExitStatus::Code(imp::WEXITSTATUS(status))
444 ExitStatus::Signal(imp::WTERMSIG(status))