1 // Copyright 2016 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 os::unix::prelude::*;
13 use ffi::{OsString, OsStr, CString, CStr};
16 use libc::{self, c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
18 use sys::fd::FileDesc;
19 use sys::fs::{File, OpenOptions};
20 use sys::pipe::{self, AnonPipe};
21 use sys_common::process::{CommandEnv, DefaultEnvKey};
22 use collections::BTreeMap;
24 ////////////////////////////////////////////////////////////////////////////////
26 ////////////////////////////////////////////////////////////////////////////////
29 // Currently we try hard to ensure that the call to `.exec()` doesn't
30 // actually allocate any memory. While many platforms try to ensure that
31 // memory allocation works after a fork in a multithreaded process, it's
32 // been observed to be buggy and somewhat unreliable, so we do our best to
33 // just not do it at all!
35 // Along those lines, the `argv` and `envp` raw pointers here are exactly
36 // what's gonna get passed to `execvp`. The `argv` array starts with the
37 // `program` and ends with a NULL, and the `envp` pointer, if present, is
38 // also null-terminated.
40 // Right now we don't support removing arguments, so there's no much fancy
41 // support there, but we support adding and removing environment variables,
42 // so a side table is used to track where in the `envp` array each key is
43 // located. Whenever we add a key we update it in place if it's already
44 // present, and whenever we remove a key we update the locations of all
49 env: CommandEnv<DefaultEnvKey>,
55 closures: Vec<Box<FnMut() -> io::Result<()> + Send + Sync>>,
57 stdout: Option<Stdio>,
58 stderr: Option<Stdio>,
61 // Create a new type for argv, so that we can make it `Send`
62 struct Argv(Vec<*const c_char>);
64 // It is safe to make Argv Send, because it contains pointers to memory owned by `Command.args`
65 unsafe impl Send for Argv {}
67 // passed back to std::process with the pipes connected to the child, if any
69 pub struct StdioPipes {
70 pub stdin: Option<AnonPipe>,
71 pub stdout: Option<AnonPipe>,
72 pub stderr: Option<AnonPipe>,
75 // passed to do_exec() with configuration of what the child stdio should look
77 pub struct ChildPipes {
78 pub stdin: ChildStdio,
79 pub stdout: ChildStdio,
80 pub stderr: ChildStdio,
97 pub fn new(program: &OsStr) -> Command {
98 let mut saw_nul = false;
99 let program = os2c(program, &mut saw_nul);
101 argv: Argv(vec![program.as_ptr(), ptr::null()]),
104 env: Default::default(),
109 closures: Vec::new(),
116 pub fn arg(&mut self, arg: &OsStr) {
117 // Overwrite the trailing NULL pointer in `argv` and then add a new null
119 let arg = os2c(arg, &mut self.saw_nul);
120 self.argv.0[self.args.len() + 1] = arg.as_ptr();
121 self.argv.0.push(ptr::null());
123 // Also make sure we keep track of the owned value to schedule a
124 // destructor for this memory.
128 pub fn cwd(&mut self, dir: &OsStr) {
129 self.cwd = Some(os2c(dir, &mut self.saw_nul));
131 pub fn uid(&mut self, id: uid_t) {
134 pub fn gid(&mut self, id: gid_t) {
138 pub fn saw_nul(&self) -> bool {
141 pub fn get_argv(&self) -> &Vec<*const c_char> {
146 pub fn get_cwd(&self) -> &Option<CString> {
150 pub fn get_uid(&self) -> Option<uid_t> {
154 pub fn get_gid(&self) -> Option<gid_t> {
158 pub fn get_closures(&mut self) -> &mut Vec<Box<FnMut() -> io::Result<()> + Send + Sync>> {
162 pub fn before_exec(&mut self,
163 f: Box<FnMut() -> io::Result<()> + Send + Sync>) {
164 self.closures.push(f);
167 pub fn stdin(&mut self, stdin: Stdio) {
168 self.stdin = Some(stdin);
171 pub fn stdout(&mut self, stdout: Stdio) {
172 self.stdout = Some(stdout);
175 pub fn stderr(&mut self, stderr: Stdio) {
176 self.stderr = Some(stderr);
179 pub fn env_mut(&mut self) -> &mut CommandEnv<DefaultEnvKey> {
183 pub fn capture_env(&mut self) -> Option<CStringArray> {
184 let maybe_env = self.env.capture_if_changed();
185 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
188 pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
189 -> io::Result<(StdioPipes, ChildPipes)> {
190 let null = Stdio::Null;
191 let default_stdin = if needs_stdin {&default} else {&null};
192 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
193 let stdout = self.stdout.as_ref().unwrap_or(&default);
194 let stderr = self.stderr.as_ref().unwrap_or(&default);
195 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
196 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
197 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
198 let ours = StdioPipes {
203 let theirs = ChildPipes {
205 stdout: their_stdout,
206 stderr: their_stderr,
212 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
213 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
215 CString::new("<string-with-nul>").unwrap()
219 // Helper type to manage ownership of the strings within a C-style array.
220 pub struct CStringArray {
222 ptrs: Vec<*const c_char>
226 pub fn with_capacity(capacity: usize) -> Self {
227 let mut result = CStringArray {
228 items: Vec::with_capacity(capacity),
229 ptrs: Vec::with_capacity(capacity+1)
231 result.ptrs.push(ptr::null());
234 pub fn push(&mut self, item: CString) {
235 let l = self.ptrs.len();
236 self.ptrs[l-1] = item.as_ptr();
237 self.ptrs.push(ptr::null());
238 self.items.push(item);
240 pub fn as_ptr(&self) -> *const *const c_char {
245 fn construct_envp(env: BTreeMap<DefaultEnvKey, OsString>, saw_nul: &mut bool) -> CStringArray {
246 let mut result = CStringArray::with_capacity(env.len());
248 let mut k: OsString = k.into();
250 // Reserve additional space for '=' and null terminator
251 k.reserve_exact(v.len() + 2);
255 // Add the new entry into the array
256 if let Ok(item) = CString::new(k.into_vec()) {
267 pub fn to_child_stdio(&self, readable: bool)
268 -> io::Result<(ChildStdio, Option<AnonPipe>)> {
271 Ok((ChildStdio::Inherit, None))
274 // Make sure that the source descriptors are not an stdio
275 // descriptor, otherwise the order which we set the child's
276 // descriptors may blow away a descriptor which we are hoping to
277 // save. For example, suppose we want the child's stderr to be the
278 // parent's stdout, and the child's stdout to be the parent's
279 // stderr. No matter which we dup first, the second will get
280 // overwritten prematurely.
281 Stdio::Fd(ref fd) => {
282 if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
283 Ok((ChildStdio::Owned(fd.duplicate()?), None))
285 Ok((ChildStdio::Explicit(fd.raw()), None))
290 let (reader, writer) = pipe::anon_pipe()?;
291 let (ours, theirs) = if readable {
296 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
300 let mut opts = OpenOptions::new();
302 opts.write(!readable);
304 CStr::from_ptr("/dev/null\0".as_ptr() as *const _)
306 let fd = File::open_c(&path, &opts)?;
307 Ok((ChildStdio::Owned(fd.into_fd()), None))
313 impl From<AnonPipe> for Stdio {
314 fn from(pipe: AnonPipe) -> Stdio {
315 Stdio::Fd(pipe.into_fd())
319 impl From<File> for Stdio {
320 fn from(file: File) -> Stdio {
321 Stdio::Fd(file.into_fd())
326 pub fn fd(&self) -> Option<c_int> {
328 ChildStdio::Inherit => None,
329 ChildStdio::Explicit(fd) => Some(fd),
330 ChildStdio::Owned(ref fd) => Some(fd.raw()),
335 impl fmt::Debug for Command {
336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337 write!(f, "{:?}", self.program)?;
338 for arg in &self.args {
339 write!(f, " {:?}", arg)?;
345 /// Unix exit statuses
346 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
347 pub struct ExitStatus(c_int);
350 pub fn new(status: c_int) -> ExitStatus {
354 fn exited(&self) -> bool {
355 unsafe { libc::WIFEXITED(self.0) }
358 pub fn success(&self) -> bool {
359 self.code() == Some(0)
362 pub fn code(&self) -> Option<i32> {
364 Some(unsafe { libc::WEXITSTATUS(self.0) })
370 pub fn signal(&self) -> Option<i32> {
372 Some(unsafe { libc::WTERMSIG(self.0) })
379 impl From<c_int> for ExitStatus {
380 fn from(a: c_int) -> ExitStatus {
385 impl fmt::Display for ExitStatus {
386 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387 if let Some(code) = self.code() {
388 write!(f, "exit code: {}", code)
390 let signal = self.signal().unwrap();
391 write!(f, "signal: {}", signal)
396 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
397 pub struct ExitCode(u8);
400 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
401 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
403 pub fn as_i32(&self) -> i32 {
408 #[cfg(all(test, not(target_os = "emscripten")))]
422 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
427 // Android with api less than 21 define sig* functions inline, so it is not
428 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
429 // to support older Android version (independent of libc version).
430 // The following implementations are based on https://git.io/vSkNf
432 #[cfg(not(target_os = "android"))]
434 #[cfg_attr(target_os = "netbsd", link_name = "__sigemptyset14")]
435 fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int;
437 #[cfg_attr(target_os = "netbsd", link_name = "__sigaddset14")]
438 fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int;
441 #[cfg(target_os = "android")]
442 unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
443 libc::memset(set as *mut _, 0, mem::size_of::<libc::sigset_t>());
447 #[cfg(target_os = "android")]
448 unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
451 let raw = slice::from_raw_parts_mut(set as *mut u8, mem::size_of::<libc::sigset_t>());
452 let bit = (signum - 1) as usize;
453 raw[bit / 8] |= 1 << (bit % 8);
457 // See #14232 for more information, but it appears that signal delivery to a
458 // newly spawned process may just be raced in the macOS, so to prevent this
459 // test from being flaky we ignore it on macOS.
461 #[cfg_attr(target_os = "macos", ignore)]
462 // When run under our current QEMU emulation test suite this test fails,
463 // although the reason isn't very clear as to why. For now this test is
465 #[cfg_attr(target_arch = "arm", ignore)]
466 #[cfg_attr(target_arch = "aarch64", ignore)]
467 fn test_process_mask() {
469 // Test to make sure that a signal mask does not get inherited.
470 let mut cmd = Command::new(OsStr::new("cat"));
472 let mut set: libc::sigset_t = mem::uninitialized();
473 let mut old_set: libc::sigset_t = mem::uninitialized();
474 t!(cvt(sigemptyset(&mut set)));
475 t!(cvt(sigaddset(&mut set, libc::SIGINT)));
476 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set, &mut old_set)));
478 cmd.stdin(Stdio::MakePipe);
479 cmd.stdout(Stdio::MakePipe);
481 let (mut cat, mut pipes) = t!(cmd.spawn(Stdio::Null, true));
482 let stdin_write = pipes.stdin.take().unwrap();
483 let stdout_read = pipes.stdout.take().unwrap();
485 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &old_set,
488 t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
489 // We need to wait until SIGINT is definitely delivered. The
490 // easiest way is to write something to cat, and try to read it
491 // back: if SIGINT is unmasked, it'll get delivered when cat is
493 let _ = stdin_write.write(b"Hello");
496 // Either EOF or failure (EPIPE) is okay.
497 let mut buf = [0; 5];
498 if let Ok(ret) = stdout_read.read(&mut buf) {