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<dyn 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<dyn FnMut() -> io::Result<()> + Send + Sync>> {
162 pub fn before_exec(&mut self,
163 f: Box<dyn 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 env_saw_path(&self) -> bool {
189 self.env.have_changed_path()
192 pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
193 -> io::Result<(StdioPipes, ChildPipes)> {
194 let null = Stdio::Null;
195 let default_stdin = if needs_stdin {&default} else {&null};
196 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
197 let stdout = self.stdout.as_ref().unwrap_or(&default);
198 let stderr = self.stderr.as_ref().unwrap_or(&default);
199 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
200 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
201 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
202 let ours = StdioPipes {
207 let theirs = ChildPipes {
209 stdout: their_stdout,
210 stderr: their_stderr,
216 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
217 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
219 CString::new("<string-with-nul>").unwrap()
223 // Helper type to manage ownership of the strings within a C-style array.
224 pub struct CStringArray {
226 ptrs: Vec<*const c_char>
230 pub fn with_capacity(capacity: usize) -> Self {
231 let mut result = CStringArray {
232 items: Vec::with_capacity(capacity),
233 ptrs: Vec::with_capacity(capacity+1)
235 result.ptrs.push(ptr::null());
238 pub fn push(&mut self, item: CString) {
239 let l = self.ptrs.len();
240 self.ptrs[l-1] = item.as_ptr();
241 self.ptrs.push(ptr::null());
242 self.items.push(item);
244 pub fn as_ptr(&self) -> *const *const c_char {
249 fn construct_envp(env: BTreeMap<DefaultEnvKey, OsString>, saw_nul: &mut bool) -> CStringArray {
250 let mut result = CStringArray::with_capacity(env.len());
252 let mut k: OsString = k.into();
254 // Reserve additional space for '=' and null terminator
255 k.reserve_exact(v.len() + 2);
259 // Add the new entry into the array
260 if let Ok(item) = CString::new(k.into_vec()) {
271 pub fn to_child_stdio(&self, readable: bool)
272 -> io::Result<(ChildStdio, Option<AnonPipe>)> {
275 Ok((ChildStdio::Inherit, None))
278 // Make sure that the source descriptors are not an stdio
279 // descriptor, otherwise the order which we set the child's
280 // descriptors may blow away a descriptor which we are hoping to
281 // save. For example, suppose we want the child's stderr to be the
282 // parent's stdout, and the child's stdout to be the parent's
283 // stderr. No matter which we dup first, the second will get
284 // overwritten prematurely.
285 Stdio::Fd(ref fd) => {
286 if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
287 Ok((ChildStdio::Owned(fd.duplicate()?), None))
289 Ok((ChildStdio::Explicit(fd.raw()), None))
294 let (reader, writer) = pipe::anon_pipe()?;
295 let (ours, theirs) = if readable {
300 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
304 let mut opts = OpenOptions::new();
306 opts.write(!readable);
308 CStr::from_ptr("/dev/null\0".as_ptr() as *const _)
310 let fd = File::open_c(&path, &opts)?;
311 Ok((ChildStdio::Owned(fd.into_fd()), None))
317 impl From<AnonPipe> for Stdio {
318 fn from(pipe: AnonPipe) -> Stdio {
319 Stdio::Fd(pipe.into_fd())
323 impl From<File> for Stdio {
324 fn from(file: File) -> Stdio {
325 Stdio::Fd(file.into_fd())
330 pub fn fd(&self) -> Option<c_int> {
332 ChildStdio::Inherit => None,
333 ChildStdio::Explicit(fd) => Some(fd),
334 ChildStdio::Owned(ref fd) => Some(fd.raw()),
339 impl fmt::Debug for Command {
340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341 write!(f, "{:?}", self.program)?;
342 for arg in &self.args {
343 write!(f, " {:?}", arg)?;
349 /// Unix exit statuses
350 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
351 pub struct ExitStatus(c_int);
354 pub fn new(status: c_int) -> ExitStatus {
358 fn exited(&self) -> bool {
359 unsafe { libc::WIFEXITED(self.0) }
362 pub fn success(&self) -> bool {
363 self.code() == Some(0)
366 pub fn code(&self) -> Option<i32> {
368 Some(unsafe { libc::WEXITSTATUS(self.0) })
374 pub fn signal(&self) -> Option<i32> {
376 Some(unsafe { libc::WTERMSIG(self.0) })
383 impl From<c_int> for ExitStatus {
384 fn from(a: c_int) -> ExitStatus {
389 impl fmt::Display for ExitStatus {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 if let Some(code) = self.code() {
392 write!(f, "exit code: {}", code)
394 let signal = self.signal().unwrap();
395 write!(f, "signal: {}", signal)
400 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
401 pub struct ExitCode(u8);
404 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
405 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
408 pub fn as_i32(&self) -> i32 {
413 #[cfg(all(test, not(target_os = "emscripten")))]
427 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
432 // Android with api less than 21 define sig* functions inline, so it is not
433 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
434 // to support older Android version (independent of libc version).
435 // The following implementations are based on https://git.io/vSkNf
437 #[cfg(not(target_os = "android"))]
439 #[cfg_attr(target_os = "netbsd", link_name = "__sigemptyset14")]
440 fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int;
442 #[cfg_attr(target_os = "netbsd", link_name = "__sigaddset14")]
443 fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int;
446 #[cfg(target_os = "android")]
447 unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
448 libc::memset(set as *mut _, 0, mem::size_of::<libc::sigset_t>());
452 #[cfg(target_os = "android")]
453 unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
456 let raw = slice::from_raw_parts_mut(set as *mut u8, mem::size_of::<libc::sigset_t>());
457 let bit = (signum - 1) as usize;
458 raw[bit / 8] |= 1 << (bit % 8);
462 // See #14232 for more information, but it appears that signal delivery to a
463 // newly spawned process may just be raced in the macOS, so to prevent this
464 // test from being flaky we ignore it on macOS.
466 #[cfg_attr(target_os = "macos", ignore)]
467 // When run under our current QEMU emulation test suite this test fails,
468 // although the reason isn't very clear as to why. For now this test is
470 #[cfg_attr(target_arch = "arm", ignore)]
471 #[cfg_attr(target_arch = "aarch64", ignore)]
472 fn test_process_mask() {
474 // Test to make sure that a signal mask does not get inherited.
475 let mut cmd = Command::new(OsStr::new("cat"));
477 let mut set: libc::sigset_t = mem::uninitialized();
478 let mut old_set: libc::sigset_t = mem::uninitialized();
479 t!(cvt(sigemptyset(&mut set)));
480 t!(cvt(sigaddset(&mut set, libc::SIGINT)));
481 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set, &mut old_set)));
483 cmd.stdin(Stdio::MakePipe);
484 cmd.stdout(Stdio::MakePipe);
486 let (mut cat, mut pipes) = t!(cmd.spawn(Stdio::Null, true));
487 let stdin_write = pipes.stdin.take().unwrap();
488 let stdout_read = pipes.stdout.take().unwrap();
490 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &old_set,
493 t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
494 // We need to wait until SIGINT is definitely delivered. The
495 // easiest way is to write something to cat, and try to read it
496 // back: if SIGINT is unmasked, it'll get delivered when cat is
498 let _ = stdin_write.write(b"Hello");
501 // Either EOF or failure (EPIPE) is okay.
502 let mut buf = [0; 5];
503 if let Ok(ret) = stdout_read.read(&mut buf) {