1 use crate::os::unix::prelude::*;
3 use crate::ffi::{OsString, OsStr, CString};
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"))]
16 crate::sys::fs::OpenOptions,
19 use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
22 if #[cfg(target_os = "fuchsia")] {
23 // fuchsia doesn't have /dev/null
24 } else if #[cfg(target_os = "redox")] {
25 const DEV_NULL: &'static str = "null:\0";
27 const DEV_NULL: &'static str = "/dev/null\0";
31 // Android with api less than 21 define sig* functions inline, so it is not
32 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
33 // to support older Android version (independent of libc version).
34 // The following implementations are based on https://git.io/vSkNf
36 if #[cfg(target_os = "android")] {
37 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
38 set.write_bytes(0u8, 1);
42 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
43 use crate::{slice, mem};
45 let raw = slice::from_raw_parts_mut(set as *mut u8, mem::size_of::<libc::sigset_t>());
46 let bit = (signum - 1) as usize;
47 raw[bit / 8] |= 1 << (bit % 8);
51 pub use libc::{sigemptyset, sigaddset};
55 ////////////////////////////////////////////////////////////////////////////////
57 ////////////////////////////////////////////////////////////////////////////////
60 // Currently we try hard to ensure that the call to `.exec()` doesn't
61 // actually allocate any memory. While many platforms try to ensure that
62 // memory allocation works after a fork in a multithreaded process, it's
63 // been observed to be buggy and somewhat unreliable, so we do our best to
64 // just not do it at all!
66 // Along those lines, the `argv` and `envp` raw pointers here are exactly
67 // what's gonna get passed to `execvp`. The `argv` array starts with the
68 // `program` and ends with a NULL, and the `envp` pointer, if present, is
69 // also null-terminated.
71 // Right now we don't support removing arguments, so there's no much fancy
72 // support there, but we support adding and removing environment variables,
73 // so a side table is used to track where in the `envp` array each key is
74 // located. Whenever we add a key we update it in place if it's already
75 // present, and whenever we remove a key we update the locations of all
86 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
88 stdout: Option<Stdio>,
89 stderr: Option<Stdio>,
92 // Create a new type for argv, so that we can make it `Send`
93 struct Argv(Vec<*const c_char>);
95 // It is safe to make Argv Send, because it contains pointers to memory owned by `Command.args`
96 unsafe impl Send for Argv {}
98 // passed back to std::process with the pipes connected to the child, if any
100 pub struct StdioPipes {
101 pub stdin: Option<AnonPipe>,
102 pub stdout: Option<AnonPipe>,
103 pub stderr: Option<AnonPipe>,
106 // passed to do_exec() with configuration of what the child stdio should look
108 pub struct ChildPipes {
109 pub stdin: ChildStdio,
110 pub stdout: ChildStdio,
111 pub stderr: ChildStdio,
114 pub enum ChildStdio {
119 // On Fuchsia, null stdio is the default, so we simply don't specify
120 // any actions at the time of spawning.
121 #[cfg(target_os = "fuchsia")]
133 pub fn new(program: &OsStr) -> Command {
134 let mut saw_nul = false;
135 let program = os2c(program, &mut saw_nul);
137 argv: Argv(vec![program.as_ptr(), ptr::null()]),
140 env: Default::default(),
145 closures: Vec::new(),
152 pub fn arg(&mut self, arg: &OsStr) {
153 // Overwrite the trailing NULL pointer in `argv` and then add a new null
155 let arg = os2c(arg, &mut self.saw_nul);
156 self.argv.0[self.args.len() + 1] = arg.as_ptr();
157 self.argv.0.push(ptr::null());
159 // Also make sure we keep track of the owned value to schedule a
160 // destructor for this memory.
164 pub fn cwd(&mut self, dir: &OsStr) {
165 self.cwd = Some(os2c(dir, &mut self.saw_nul));
167 pub fn uid(&mut self, id: uid_t) {
170 pub fn gid(&mut self, id: gid_t) {
174 pub fn saw_nul(&self) -> bool {
177 pub fn get_argv(&self) -> &Vec<*const c_char> {
182 pub fn get_cwd(&self) -> &Option<CString> {
186 pub fn get_uid(&self) -> Option<uid_t> {
190 pub fn get_gid(&self) -> Option<gid_t> {
194 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
198 pub unsafe fn pre_exec(
200 f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
202 self.closures.push(f);
205 pub fn stdin(&mut self, stdin: Stdio) {
206 self.stdin = Some(stdin);
209 pub fn stdout(&mut self, stdout: Stdio) {
210 self.stdout = Some(stdout);
213 pub fn stderr(&mut self, stderr: Stdio) {
214 self.stderr = Some(stderr);
217 pub fn env_mut(&mut self) -> &mut CommandEnv {
221 pub fn capture_env(&mut self) -> Option<CStringArray> {
222 let maybe_env = self.env.capture_if_changed();
223 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
226 pub fn env_saw_path(&self) -> bool {
227 self.env.have_changed_path()
230 pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
231 -> io::Result<(StdioPipes, ChildPipes)> {
232 let null = Stdio::Null;
233 let default_stdin = if needs_stdin {&default} else {&null};
234 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
235 let stdout = self.stdout.as_ref().unwrap_or(&default);
236 let stderr = self.stderr.as_ref().unwrap_or(&default);
237 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
238 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
239 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
240 let ours = StdioPipes {
245 let theirs = ChildPipes {
247 stdout: their_stdout,
248 stderr: their_stderr,
254 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
255 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
257 CString::new("<string-with-nul>").unwrap()
261 // Helper type to manage ownership of the strings within a C-style array.
262 pub struct CStringArray {
264 ptrs: Vec<*const c_char>
268 pub fn with_capacity(capacity: usize) -> Self {
269 let mut result = CStringArray {
270 items: Vec::with_capacity(capacity),
271 ptrs: Vec::with_capacity(capacity+1)
273 result.ptrs.push(ptr::null());
276 pub fn push(&mut self, item: CString) {
277 let l = self.ptrs.len();
278 self.ptrs[l-1] = item.as_ptr();
279 self.ptrs.push(ptr::null());
280 self.items.push(item);
282 pub fn as_ptr(&self) -> *const *const c_char {
287 fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
288 let mut result = CStringArray::with_capacity(env.len());
290 let mut k: OsString = k.into();
292 // Reserve additional space for '=' and null terminator
293 k.reserve_exact(v.len() + 2);
297 // Add the new entry into the array
298 if let Ok(item) = CString::new(k.into_vec()) {
309 pub fn to_child_stdio(&self, readable: bool)
310 -> io::Result<(ChildStdio, Option<AnonPipe>)> {
313 Ok((ChildStdio::Inherit, None))
316 // Make sure that the source descriptors are not an stdio
317 // descriptor, otherwise the order which we set the child's
318 // descriptors may blow away a descriptor which we are hoping to
319 // save. For example, suppose we want the child's stderr to be the
320 // parent's stdout, and the child's stdout to be the parent's
321 // stderr. No matter which we dup first, the second will get
322 // overwritten prematurely.
323 Stdio::Fd(ref fd) => {
324 if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
325 Ok((ChildStdio::Owned(fd.duplicate()?), None))
327 Ok((ChildStdio::Explicit(fd.raw()), None))
332 let (reader, writer) = pipe::anon_pipe()?;
333 let (ours, theirs) = if readable {
338 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
341 #[cfg(not(target_os = "fuchsia"))]
343 let mut opts = OpenOptions::new();
345 opts.write(!readable);
347 CStr::from_ptr(DEV_NULL.as_ptr() as *const _)
349 let fd = File::open_c(&path, &opts)?;
350 Ok((ChildStdio::Owned(fd.into_fd()), None))
353 #[cfg(target_os = "fuchsia")]
355 Ok((ChildStdio::Null, None))
361 impl From<AnonPipe> for Stdio {
362 fn from(pipe: AnonPipe) -> Stdio {
363 Stdio::Fd(pipe.into_fd())
367 impl From<File> for Stdio {
368 fn from(file: File) -> Stdio {
369 Stdio::Fd(file.into_fd())
374 pub fn fd(&self) -> Option<c_int> {
376 ChildStdio::Inherit => None,
377 ChildStdio::Explicit(fd) => Some(fd),
378 ChildStdio::Owned(ref fd) => Some(fd.raw()),
380 #[cfg(target_os = "fuchsia")]
381 ChildStdio::Null => None,
386 impl fmt::Debug for Command {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388 write!(f, "{:?}", self.program)?;
389 for arg in &self.args {
390 write!(f, " {:?}", arg)?;
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 _);
404 pub fn as_i32(&self) -> i32 {
409 #[cfg(all(test, not(target_os = "emscripten")))]
413 use crate::ffi::OsStr;
422 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
427 // See #14232 for more information, but it appears that signal delivery to a
428 // newly spawned process may just be raced in the macOS, so to prevent this
429 // test from being flaky we ignore it on macOS.
431 #[cfg_attr(target_os = "macos", ignore)]
432 // When run under our current QEMU emulation test suite this test fails,
433 // although the reason isn't very clear as to why. For now this test is
435 #[cfg_attr(target_arch = "arm", ignore)]
436 #[cfg_attr(target_arch = "aarch64", ignore)]
437 fn test_process_mask() {
439 // Test to make sure that a signal mask does not get inherited.
440 let mut cmd = Command::new(OsStr::new("cat"));
442 let mut set = mem::MaybeUninit::<libc::sigset_t>::uninit();
443 let mut old_set = mem::MaybeUninit::<libc::sigset_t>::uninit();
444 t!(cvt(sigemptyset(set.as_mut_ptr())));
445 t!(cvt(sigaddset(set.as_mut_ptr(), libc::SIGINT)));
446 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), old_set.as_mut_ptr())));
448 cmd.stdin(Stdio::MakePipe);
449 cmd.stdout(Stdio::MakePipe);
451 let (mut cat, mut pipes) = t!(cmd.spawn(Stdio::Null, true));
452 let stdin_write = pipes.stdin.take().unwrap();
453 let stdout_read = pipes.stdout.take().unwrap();
455 t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(),
458 t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
459 // We need to wait until SIGINT is definitely delivered. The
460 // easiest way is to write something to cat, and try to read it
461 // back: if SIGINT is unmasked, it'll get delivered when cat is
463 let _ = stdin_write.write(b"Hello");
466 // Either EOF or failure (EPIPE) is okay.
467 let mut buf = [0; 5];
468 if let Ok(ret) = stdout_read.read(&mut buf) {