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.
12 use os::unix::prelude::*;
14 use collections::HashMap;
16 use ffi::{OsString, OsStr, CString};
18 use io::{self, Error, ErrorKind};
19 use libc::{self, pid_t, c_void, c_int, gid_t, uid_t};
22 use sys::pipe2::AnonPipe;
23 use sys::{self, retry, c, cvt};
25 ////////////////////////////////////////////////////////////////////////////////
27 ////////////////////////////////////////////////////////////////////////////////
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
41 pub fn new(program: &OsStr) -> Command {
43 program: program.to_cstring().unwrap(),
53 pub fn arg(&mut self, arg: &OsStr) {
54 self.args.push(arg.to_cstring().unwrap())
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()))
59 fn init_env_map(&mut self) {
60 if self.env.is_none() {
61 self.env = Some(env::vars_os().collect());
64 pub fn env(&mut self, key: &OsStr, val: &OsStr) {
66 self.env.as_mut().unwrap().insert(key.to_os_string(), val.to_os_string());
68 pub fn env_remove(&mut self, key: &OsStr) {
70 self.env.as_mut().unwrap().remove(&key.to_os_string());
72 pub fn env_clear(&mut self) {
73 self.env = Some(HashMap::new())
75 pub fn cwd(&mut self, dir: &OsStr) {
76 self.cwd = Some(dir.to_cstring().unwrap())
80 ////////////////////////////////////////////////////////////////////////////////
82 ////////////////////////////////////////////////////////////////////////////////
84 /// Unix exit statuses
85 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
87 /// Normal termination with an exit code.
90 /// Termination by signal, with the signal number.
92 /// Never generated on Windows.
97 pub fn success(&self) -> bool {
98 *self == ExitStatus::Code(0)
100 pub fn code(&self) -> Option<i32> {
102 ExitStatus::Code(c) => Some(c),
108 impl fmt::Display for ExitStatus {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 ExitStatus::Code(code) => write!(f, "exit code: {}", code),
112 ExitStatus::Signal(code) => write!(f, "signal: {}", code),
117 /// The unique id of the process (this should never be negative).
122 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
125 pub unsafe fn kill(&self) -> io::Result<()> {
126 try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL)));
130 pub fn spawn(cfg: &Command,
131 in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>)
132 -> io::Result<Process>
134 use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
138 pub fn rust_unset_sigprocmask();
142 unsafe fn set_cloexec(fd: c_int) {
143 let ret = c::ioctl(fd, c::FIOCLEX);
147 #[cfg(all(target_os = "android", target_arch = "aarch64"))]
148 unsafe fn getdtablesize() -> c_int {
149 libc::sysconf(libc::consts::os::sysconf::_SC_OPEN_MAX) as c_int
152 #[cfg(not(all(target_os = "android", target_arch = "aarch64")))]
153 unsafe fn getdtablesize() -> c_int {
154 libc::funcs::bsd44::getdtablesize()
157 let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
159 with_envp(cfg.env.as_ref(), |envp: *const c_void| {
160 with_argv(&cfg.program, &cfg.args, |argv: *const *const libc::c_char| unsafe {
161 let (input, mut output) = try!(sys::pipe2::anon_pipe());
163 // We may use this in the child, so perform allocations before the
165 let devnull = b"/dev/null\0";
167 set_cloexec(output.raw());
171 return Err(Error::last_os_error())
174 fn combine(arr: &[u8]) -> i32 {
175 let a = arr[0] as u32;
176 let b = arr[1] as u32;
177 let c = arr[2] as u32;
178 let d = arr[3] as u32;
180 ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
183 let p = Process{ pid: pid };
185 let mut bytes = [0; 8];
187 // loop to handle EINTER
189 match input.read(&mut bytes) {
191 assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
192 "Validation on the CLOEXEC pipe failed: {:?}", bytes);
193 let errno = combine(&bytes[0.. 4]);
194 assert!(p.wait().is_ok(),
195 "wait() should either return Ok or panic");
196 return Err(Error::from_os_error(errno))
198 Ok(0) => return Ok(p),
199 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
201 assert!(p.wait().is_ok(),
202 "wait() should either return Ok or panic");
203 panic!("the CLOEXEC pipe failed: {:?}", e)
205 Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
206 assert!(p.wait().is_ok(),
207 "wait() should either return Ok or panic");
208 panic!("short read on the CLOEXEC pipe")
214 // And at this point we've reached a special time in the life of the
215 // child. The child must now be considered hamstrung and unable to
216 // do anything other than syscalls really. Consider the following
219 // 1. Thread A of process 1 grabs the malloc() mutex
220 // 2. Thread B of process 1 forks(), creating thread C
221 // 3. Thread C of process 2 then attempts to malloc()
222 // 4. The memory of process 2 is the same as the memory of
223 // process 1, so the mutex is locked.
225 // This situation looks a lot like deadlock, right? It turns out
226 // that this is what pthread_atfork() takes care of, which is
227 // presumably implemented across platforms. The first thing that
228 // threads to *before* forking is to do things like grab the malloc
229 // mutex, and then after the fork they unlock it.
231 // Despite this information, libnative's spawn has been witnessed to
232 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
233 // all collected backtraces point at malloc/free traffic in the
234 // child spawned process.
236 // For this reason, the block of code below should contain 0
237 // invocations of either malloc of free (or their related friends).
239 // As an example of not having malloc/free traffic, we don't close
240 // this file descriptor by dropping the FileDesc (which contains an
241 // allocation). Instead we just close it manually. This will never
242 // have the drop glue anyway because this code never returns (the
243 // child will either exec() or invoke libc::exit)
244 let _ = libc::close(input.raw());
246 fn fail(output: &mut AnonPipe) -> ! {
247 let errno = sys::os::errno() as u32;
253 CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
254 CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
256 // pipe I/O up to PIPE_BUF bytes should be atomic
257 assert!(output.write(&bytes).is_ok());
258 unsafe { libc::_exit(1) }
261 rustrt::rust_unset_sigprocmask();
263 // If a stdio file descriptor is set to be ignored, we don't
264 // actually close it, but rather open up /dev/null into that
265 // file descriptor. Otherwise, the first file descriptor opened
266 // up in the child would be numbered as one of the stdio file
267 // descriptors, which is likely to wreak havoc.
268 let setup = |src: Option<AnonPipe>, dst: c_int| {
269 let src = match src {
271 let flags = if dst == libc::STDIN_FILENO {
276 libc::open(devnull.as_ptr() as *const _, flags, 0)
280 // Leak the memory and the file descriptor. We're in the
281 // child now an all our resources are going to be
282 // cleaned up very soon
287 src != -1 && retry(|| dup2(src, dst)) != -1
290 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
291 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
292 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
294 // close all other fds
295 for fd in (3..getdtablesize()).rev() {
296 if fd != output.raw() {
297 let _ = close(fd as c_int);
303 if libc::setgid(u as libc::gid_t) != 0 {
311 // When dropping privileges from root, the `setgroups` call
312 // will remove any extraneous groups. If we don't call this,
313 // then even though our uid has dropped, we may still have
314 // groups that enable us to do super-user things. This will
315 // fail if we aren't root, so don't bother checking the
316 // return value, this is just done as an optimistic
317 // privilege dropping function.
319 fn setgroups(ngroups: libc::c_int,
320 ptr: *const libc::c_void) -> libc::c_int;
322 let _ = setgroups(0, ptr::null());
324 if libc::setuid(u as libc::uid_t) != 0 {
331 // Don't check the error of setsid because it fails if we're the
332 // process leader already. We just forked so it shouldn't return
333 // error, but ignore it anyway.
334 let _ = libc::setsid();
336 if !dirp.is_null() && chdir(dirp) == -1 {
340 *sys::os::environ() = envp as *const _;
342 let _ = execvp(*argv, argv as *mut _);
348 pub fn wait(&self) -> io::Result<ExitStatus> {
349 let mut status = 0 as c_int;
350 try!(cvt(retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) })));
351 Ok(translate_status(status))
354 pub fn try_wait(&self) -> Option<ExitStatus> {
355 let mut status = 0 as c_int;
356 match retry(|| unsafe {
357 c::waitpid(self.pid, &mut status, c::WNOHANG)
359 n if n == self.pid => Some(translate_status(status)),
361 n => panic!("unknown waitpid error `{:?}`: {:?}", n,
362 super::last_error()),
367 fn with_argv<T,F>(prog: &CString, args: &[CString], cb: F) -> T
368 where F : FnOnce(*const *const libc::c_char) -> T
370 let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
372 // Convert the CStrings into an array of pointers. Note: the
373 // lifetime of the various CStrings involved is guaranteed to be
374 // larger than the lifetime of our invocation of cb, but this is
375 // technically unsafe as the callback could leak these pointers
377 ptrs.push(prog.as_ptr());
378 ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
380 // Add a terminating null pointer (required by libc).
381 ptrs.push(ptr::null());
386 fn with_envp<T, F>(env: Option<&HashMap<OsString, OsString>>, cb: F) -> T
387 where F : FnOnce(*const c_void) -> T
389 // On posixy systems we can pass a char** for envp, which is a
390 // null-terminated array of "k=v\0" strings. Since we must create
391 // these strings locally, yet expose a raw pointer to them, we
392 // create a temporary vector to own the CStrings that outlives the
396 let mut tmps = Vec::with_capacity(env.len());
399 let mut kv = Vec::new();
400 kv.push_all(pair.0.as_bytes());
402 kv.push_all(pair.1.as_bytes());
403 kv.push(0); // terminating null
407 // As with `with_argv`, this is unsafe, since cb could leak the pointers.
408 let mut ptrs: Vec<*const libc::c_char> =
410 .map(|tmp| tmp.as_ptr() as *const libc::c_char)
412 ptrs.push(ptr::null());
414 cb(ptrs.as_ptr() as *const c_void)
420 fn translate_status(status: c_int) -> ExitStatus {
421 #![allow(non_snake_case)]
422 #[cfg(any(target_os = "linux", target_os = "android"))]
424 pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
425 pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
426 pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
429 #[cfg(any(target_os = "macos",
431 target_os = "freebsd",
432 target_os = "dragonfly",
433 target_os = "bitrig",
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))