1 use crate::os::unix::prelude::*;
3 use crate::ffi::{OsString, OsStr, CString, CStr};
7 use crate::sys::fd::FileDesc;
8 use crate::sys::fs::File;
9 use crate::sys::pipe::{self, AnonPipe};
10 use crate::sys_common::process::CommandEnv;
11 use crate::collections::BTreeMap;
13 #[cfg(not(target_os = "fuchsia"))]
14 use crate::sys::fs::OpenOptions;
16 use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
19 if #[cfg(target_os = "fuchsia")] {
20 // fuchsia doesn't have /dev/null
21 } else if #[cfg(target_os = "redox")] {
22 const DEV_NULL: &'static str = "null:\0";
24 const DEV_NULL: &'static str = "/dev/null\0";
28 // Android with api less than 21 define sig* functions inline, so it is not
29 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
30 // to support older Android version (independent of libc version).
31 // The following implementations are based on https://git.io/vSkNf
33 if #[cfg(target_os = "android")] {
34 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
35 set.write_bytes(0u8, 1);
39 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
40 use crate::{slice, mem};
42 let raw = slice::from_raw_parts_mut(set as *mut u8, mem::size_of::<libc::sigset_t>());
43 let bit = (signum - 1) as usize;
44 raw[bit / 8] |= 1 << (bit % 8);
48 pub use libc::{sigemptyset, sigaddset};
52 ////////////////////////////////////////////////////////////////////////////////
54 ////////////////////////////////////////////////////////////////////////////////
57 // Currently we try hard to ensure that the call to `.exec()` doesn't
58 // actually allocate any memory. While many platforms try to ensure that
59 // memory allocation works after a fork in a multithreaded process, it's
60 // been observed to be buggy and somewhat unreliable, so we do our best to
61 // just not do it at all!
63 // Along those lines, the `argv` and `envp` raw pointers here are exactly
64 // what's gonna get passed to `execvp`. The `argv` array starts with the
65 // `program` and ends with a NULL, and the `envp` pointer, if present, is
66 // also null-terminated.
68 // Right now we don't support removing arguments, so there's no much fancy
69 // support there, but we support adding and removing environment variables,
70 // so a side table is used to track where in the `envp` array each key is
71 // located. Whenever we add a key we update it in place if it's already
72 // present, and whenever we remove a key we update the locations of all
83 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
85 stdout: Option<Stdio>,
86 stderr: Option<Stdio>,
89 // Create a new type for argv, so that we can make it `Send`
90 struct Argv(Vec<*const c_char>);
92 // It is safe to make Argv Send, because it contains pointers to memory owned by `Command.args`
93 unsafe impl Send for Argv {}
95 // passed back to std::process with the pipes connected to the child, if any
97 pub struct StdioPipes {
98 pub stdin: Option<AnonPipe>,
99 pub stdout: Option<AnonPipe>,
100 pub stderr: Option<AnonPipe>,
103 // passed to do_exec() with configuration of what the child stdio should look
105 pub struct ChildPipes {
106 pub stdin: ChildStdio,
107 pub stdout: ChildStdio,
108 pub stderr: ChildStdio,
111 pub enum ChildStdio {
116 // On Fuchsia, null stdio is the default, so we simply don't specify
117 // any actions at the time of spawning.
118 #[cfg(target_os = "fuchsia")]
130 pub fn new(program: &OsStr) -> Command {
131 let mut saw_nul = false;
132 let program = os2c(program, &mut saw_nul);
134 argv: Argv(vec![program.as_ptr(), ptr::null()]),
135 args: vec![program.clone()],
137 env: Default::default(),
142 closures: Vec::new(),
149 pub fn set_arg_0(&mut self, arg: &OsStr) {
151 let arg = os2c(arg, &mut self.saw_nul);
152 debug_assert!(self.argv.0.len() > 1);
153 self.argv.0[0] = arg.as_ptr();
157 pub fn arg(&mut self, arg: &OsStr) {
158 // Overwrite the trailing NULL pointer in `argv` and then add a new null
160 let arg = os2c(arg, &mut self.saw_nul);
161 self.argv.0[self.args.len()] = arg.as_ptr();
162 self.argv.0.push(ptr::null());
164 // Also make sure we keep track of the owned value to schedule a
165 // destructor for this memory.
169 pub fn cwd(&mut self, dir: &OsStr) {
170 self.cwd = Some(os2c(dir, &mut self.saw_nul));
172 pub fn uid(&mut self, id: uid_t) {
175 pub fn gid(&mut self, id: gid_t) {
179 pub fn saw_nul(&self) -> bool {
182 pub fn get_argv(&self) -> &Vec<*const c_char> {
186 pub fn get_program(&self) -> &CStr {
191 pub fn get_cwd(&self) -> &Option<CString> {
195 pub fn get_uid(&self) -> Option<uid_t> {
199 pub fn get_gid(&self) -> Option<gid_t> {
203 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
207 pub unsafe fn pre_exec(
209 f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
211 self.closures.push(f);
214 pub fn stdin(&mut self, stdin: Stdio) {
215 self.stdin = Some(stdin);
218 pub fn stdout(&mut self, stdout: Stdio) {
219 self.stdout = Some(stdout);
222 pub fn stderr(&mut self, stderr: Stdio) {
223 self.stderr = Some(stderr);
226 pub fn env_mut(&mut self) -> &mut CommandEnv {
230 pub fn capture_env(&mut self) -> Option<CStringArray> {
231 let maybe_env = self.env.capture_if_changed();
232 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
235 pub fn env_saw_path(&self) -> bool {
236 self.env.have_changed_path()
239 pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
240 -> io::Result<(StdioPipes, ChildPipes)> {
241 let null = Stdio::Null;
242 let default_stdin = if needs_stdin {&default} else {&null};
243 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
244 let stdout = self.stdout.as_ref().unwrap_or(&default);
245 let stderr = self.stderr.as_ref().unwrap_or(&default);
246 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
247 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
248 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
249 let ours = StdioPipes {
254 let theirs = ChildPipes {
256 stdout: their_stdout,
257 stderr: their_stderr,
263 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
264 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
266 CString::new("<string-with-nul>").unwrap()
270 // Helper type to manage ownership of the strings within a C-style array.
271 pub struct CStringArray {
273 ptrs: Vec<*const c_char>
277 pub fn with_capacity(capacity: usize) -> Self {
278 let mut result = CStringArray {
279 items: Vec::with_capacity(capacity),
280 ptrs: Vec::with_capacity(capacity+1)
282 result.ptrs.push(ptr::null());
285 pub fn push(&mut self, item: CString) {
286 let l = self.ptrs.len();
287 self.ptrs[l-1] = item.as_ptr();
288 self.ptrs.push(ptr::null());
289 self.items.push(item);
291 pub fn as_ptr(&self) -> *const *const c_char {
296 fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
297 let mut result = CStringArray::with_capacity(env.len());
299 let mut k: OsString = k.into();
301 // Reserve additional space for '=' and null terminator
302 k.reserve_exact(v.len() + 2);
306 // Add the new entry into the array
307 if let Ok(item) = CString::new(k.into_vec()) {
318 pub fn to_child_stdio(&self, readable: bool)
319 -> io::Result<(ChildStdio, Option<AnonPipe>)> {
322 Ok((ChildStdio::Inherit, None))
325 // Make sure that the source descriptors are not an stdio
326 // descriptor, otherwise the order which we set the child's
327 // descriptors may blow away a descriptor which we are hoping to
328 // save. For example, suppose we want the child's stderr to be the
329 // parent's stdout, and the child's stdout to be the parent's
330 // stderr. No matter which we dup first, the second will get
331 // overwritten prematurely.
332 Stdio::Fd(ref fd) => {
333 if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
334 Ok((ChildStdio::Owned(fd.duplicate()?), None))
336 Ok((ChildStdio::Explicit(fd.raw()), None))
341 let (reader, writer) = pipe::anon_pipe()?;
342 let (ours, theirs) = if readable {
347 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
350 #[cfg(not(target_os = "fuchsia"))]
352 let mut opts = OpenOptions::new();
354 opts.write(!readable);
356 CStr::from_ptr(DEV_NULL.as_ptr() as *const _)
358 let fd = File::open_c(&path, &opts)?;
359 Ok((ChildStdio::Owned(fd.into_fd()), None))
362 #[cfg(target_os = "fuchsia")]
364 Ok((ChildStdio::Null, None))
370 impl From<AnonPipe> for Stdio {
371 fn from(pipe: AnonPipe) -> Stdio {
372 Stdio::Fd(pipe.into_fd())
376 impl From<File> for Stdio {
377 fn from(file: File) -> Stdio {
378 Stdio::Fd(file.into_fd())
383 pub fn fd(&self) -> Option<c_int> {
385 ChildStdio::Inherit => None,
386 ChildStdio::Explicit(fd) => Some(fd),
387 ChildStdio::Owned(ref fd) => Some(fd.raw()),
389 #[cfg(target_os = "fuchsia")]
390 ChildStdio::Null => None,
395 impl fmt::Debug for Command {
396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397 write!(f, "{:?}", self.program)?;
398 for arg in &self.args {
399 write!(f, " {:?}", arg)?;
405 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
406 pub struct ExitCode(u8);
409 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
410 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
413 pub fn as_i32(&self) -> i32 {
418 #[cfg(all(test, not(target_os = "emscripten")))]
422 use crate::ffi::OsStr;
431 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
436 // See #14232 for more information, but it appears that signal delivery to a
437 // newly spawned process may just be raced in the macOS, so to prevent this
438 // test from being flaky we ignore it on macOS.
440 #[cfg_attr(target_os = "macos", ignore)]
441 // When run under our current QEMU emulation test suite this test fails,
442 // although the reason isn't very clear as to why. For now this test is
444 #[cfg_attr(target_arch = "arm", ignore)]
445 #[cfg_attr(target_arch = "aarch64", ignore)]
446 fn test_process_mask() {
448 // Test to make sure that a signal mask does not get inherited.
449 let mut cmd = Command::new(OsStr::new("cat"));
451 let mut set = mem::MaybeUninit::<libc::sigset_t>::uninit();
452 let mut old_set = mem::MaybeUninit::<libc::sigset_t>::uninit();
453 t!(cvt(sigemptyset(set.as_mut_ptr())));
454 t!(cvt(sigaddset(set.as_mut_ptr(), libc::SIGINT)));
455 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), old_set.as_mut_ptr())));
457 cmd.stdin(Stdio::MakePipe);
458 cmd.stdout(Stdio::MakePipe);
460 let (mut cat, mut pipes) = t!(cmd.spawn(Stdio::Null, true));
461 let stdin_write = pipes.stdin.take().unwrap();
462 let stdout_read = pipes.stdout.take().unwrap();
464 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(),
467 t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
468 // We need to wait until SIGINT is definitely delivered. The
469 // easiest way is to write something to cat, and try to read it
470 // back: if SIGINT is unmasked, it'll get delivered when cat is
472 let _ = stdin_write.write(b"Hello");
475 // Either EOF or failure (EPIPE) is okay.
476 let mut buf = [0; 5];
477 if let Ok(ret) = stdout_read.read(&mut buf) {