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, CStr};
18 use io::{self, Error, ErrorKind};
19 use libc::{self, pid_t, c_void, c_int, gid_t, uid_t};
21 use sys::pipe::AnonPipe;
22 use sys::{self, c, cvt, cvt_r};
23 use sys::fs::{File, OpenOptions};
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).
128 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
131 pub unsafe fn kill(&self) -> io::Result<()> {
132 try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL)));
136 pub fn spawn(cfg: &Command,
139 err_fd: Stdio) -> io::Result<Process> {
140 let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
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());
150 Process::child_after_fork(cfg, output, argv, envp, dirp,
151 in_fd, out_fd, err_fd)
153 n if n < 0 => return Err(Error::last_os_error()),
158 let p = Process{ pid: pid };
160 let mut bytes = [0; 8];
162 // loop to handle EINTR
164 match input.read(&mut bytes) {
165 Ok(0) => return Ok(p),
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))
174 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
176 assert!(p.wait().is_ok(),
177 "wait() should either return Ok or panic");
178 panic!("the CLOEXEC pipe failed: {:?}", e)
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")
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;
194 ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
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
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.
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.
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.
220 // For this reason, the block of code below should contain 0
221 // invocations of either malloc of free (or their related friends).
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,
235 err_fd: Stdio) -> ! {
236 fn fail(output: &mut AnonPipe) -> ! {
237 let errno = sys::os::errno() as u32;
243 CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
244 CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
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
249 assert!(output.write(&bytes).is_ok());
250 unsafe { libc::_exit(1) }
253 let setup = |src: Stdio, dst: c_int| {
255 Stdio::Inherit => return true,
256 Stdio::Piped(pipe) => pipe.into_fd(),
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
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()
269 if let Ok(f) = File::open_c(devnull, &opts) {
276 cvt_r(|| libc::dup2(fd.raw(), dst)).is_ok()
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) }
283 if let Some(u) = cfg.gid {
284 if libc::setgid(u as libc::gid_t) != 0 {
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());
298 if libc::setuid(u as libc::uid_t) != 0 {
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();
308 if !dirp.is_null() && libc::chdir(dirp) == -1 {
312 *sys::os::environ() = envp as *const _;
314 let _ = libc::execvp(*argv, argv as *mut _);
318 pub fn id(&self) -> u32 {
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))
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)
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),
341 fn make_argv(prog: &CString, args: &[CString])
342 -> (*const *const libc::c_char, Vec<*const libc::c_char>)
344 let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
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
351 ptrs.push(prog.as_ptr());
352 ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
354 // Add a terminating null pointer (required by libc).
355 ptrs.push(ptr::null());
357 (ptrs.as_ptr(), ptrs)
360 fn make_envp(env: Option<&HashMap<OsString, OsString>>)
361 -> (*const c_void, Vec<Vec<u8>>, Vec<*const libc::c_char>)
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
368 if let Some(env) = env {
369 let mut tmps = Vec::with_capacity(env.len());
372 let mut kv = Vec::new();
373 kv.push_all(pair.0.as_bytes());
375 kv.push_all(pair.1.as_bytes());
376 kv.push(0); // terminating null
380 let mut ptrs: Vec<*const libc::c_char> =
382 .map(|tmp| tmp.as_ptr() as *const libc::c_char)
384 ptrs.push(ptr::null());
386 (ptrs.as_ptr() as *const _, tmps, ptrs)
388 (0 as *const _, Vec::new(), Vec::new())
392 fn translate_status(status: c_int) -> ExitStatus {
393 #![allow(non_snake_case)]
394 #[cfg(any(target_os = "linux", target_os = "android"))]
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 }
401 #[cfg(any(target_os = "macos",
403 target_os = "freebsd",
404 target_os = "dragonfly",
405 target_os = "bitrig",
406 target_os = "openbsd"))]
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 }
413 if imp::WIFEXITED(status) {
414 ExitStatus::Code(imp::WEXITSTATUS(status))
416 ExitStatus::Signal(imp::WTERMSIG(status))