1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::os::unix::prelude::*;
6 use crate::collections::BTreeMap;
7 use crate::ffi::{CStr, CString, OsStr, OsString};
10 use crate::path::Path;
12 use crate::sys::fd::FileDesc;
13 use crate::sys::fs::File;
14 use crate::sys::pipe::{self, AnonPipe};
15 use crate::sys_common::process::{CommandEnv, CommandEnvs};
16 use crate::sys_common::IntoInner;
18 #[cfg(not(target_os = "fuchsia"))]
19 use crate::sys::fs::OpenOptions;
21 use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS};
24 if #[cfg(target_os = "fuchsia")] {
25 // fuchsia doesn't have /dev/null
26 } else if #[cfg(target_os = "redox")] {
27 const DEV_NULL: &str = "null:\0";
28 } else if #[cfg(target_os = "vxworks")] {
29 const DEV_NULL: &str = "/null\0";
31 const DEV_NULL: &str = "/dev/null\0";
35 // Android with api less than 21 define sig* functions inline, so it is not
36 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
37 // to support older Android version (independent of libc version).
38 // The following implementations are based on
39 // https://github.com/aosp-mirror/platform_bionic/blob/ad8dcd6023294b646e5a8288c0ed431b0845da49/libc/include/android/legacy_signal_inlines.h
41 if #[cfg(target_os = "android")] {
43 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
44 set.write_bytes(0u8, 1);
49 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
51 mem::{align_of, size_of},
54 use libc::{c_ulong, sigset_t};
56 // The implementations from bionic (android libc) type pun `sigset_t` as an
57 // array of `c_ulong`. This works, but lets add a smoke check to make sure
58 // that doesn't change.
59 const _: () = assert!(
60 align_of::<c_ulong>() == align_of::<sigset_t>()
61 && (size_of::<sigset_t>() % size_of::<c_ulong>()) == 0
64 let bit = (signum - 1) as usize;
65 if set.is_null() || bit >= (8 * size_of::<sigset_t>()) {
66 crate::sys::unix::os::set_errno(libc::EINVAL);
69 let raw = slice::from_raw_parts_mut(
71 size_of::<sigset_t>() / size_of::<c_ulong>(),
73 const LONG_BIT: usize = size_of::<c_ulong>() * 8;
74 raw[bit / LONG_BIT] |= 1 << (bit % LONG_BIT);
78 pub use libc::{sigemptyset, sigaddset};
82 ////////////////////////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////////////////////////
89 /// Exactly what will be passed to `execvp`.
91 /// First element is a pointer to `program`, followed by pointers to
92 /// `args`, followed by a `null`. Be careful when modifying `program` or
93 /// `args` to properly update this as well.
97 program_kind: ProgramKind,
102 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
103 groups: Option<Box<[gid_t]>>,
104 stdin: Option<Stdio>,
105 stdout: Option<Stdio>,
106 stderr: Option<Stdio>,
107 #[cfg(target_os = "linux")]
109 pgroup: Option<pid_t>,
112 // Create a new type for argv, so that we can make it `Send` and `Sync`
113 struct Argv(Vec<*const c_char>);
115 // It is safe to make `Argv` `Send` and `Sync`, because it contains
116 // pointers to memory owned by `Command.args`
117 unsafe impl Send for Argv {}
118 unsafe impl Sync for Argv {}
120 // passed back to std::process with the pipes connected to the child, if any
122 pub struct StdioPipes {
123 pub stdin: Option<AnonPipe>,
124 pub stdout: Option<AnonPipe>,
125 pub stderr: Option<AnonPipe>,
128 // passed to do_exec() with configuration of what the child stdio should look
130 pub struct ChildPipes {
131 pub stdin: ChildStdio,
132 pub stdout: ChildStdio,
133 pub stderr: ChildStdio,
136 pub enum ChildStdio {
141 // On Fuchsia, null stdio is the default, so we simply don't specify
142 // any actions at the time of spawning.
143 #[cfg(target_os = "fuchsia")]
155 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
156 pub enum ProgramKind {
157 /// A program that would be looked up on the PATH (e.g. `ls`)
159 /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
161 /// An absolute path.
166 fn new(program: &OsStr) -> Self {
167 if program.bytes().starts_with(b"/") {
169 } else if program.bytes().contains(&b'/') {
170 // If the program has more than one component in it, it is a relative path.
179 #[cfg(not(target_os = "linux"))]
180 pub fn new(program: &OsStr) -> Command {
181 let mut saw_nul = false;
182 let program_kind = ProgramKind::new(program.as_ref());
183 let program = os2c(program, &mut saw_nul);
185 argv: Argv(vec![program.as_ptr(), ptr::null()]),
186 args: vec![program.clone()],
189 env: Default::default(),
194 closures: Vec::new(),
203 #[cfg(target_os = "linux")]
204 pub fn new(program: &OsStr) -> Command {
205 let mut saw_nul = false;
206 let program_kind = ProgramKind::new(program.as_ref());
207 let program = os2c(program, &mut saw_nul);
209 argv: Argv(vec![program.as_ptr(), ptr::null()]),
210 args: vec![program.clone()],
213 env: Default::default(),
218 closures: Vec::new(),
228 pub fn set_arg_0(&mut self, arg: &OsStr) {
230 let arg = os2c(arg, &mut self.saw_nul);
231 debug_assert!(self.argv.0.len() > 1);
232 self.argv.0[0] = arg.as_ptr();
236 pub fn arg(&mut self, arg: &OsStr) {
237 // Overwrite the trailing null pointer in `argv` and then add a new null
239 let arg = os2c(arg, &mut self.saw_nul);
240 self.argv.0[self.args.len()] = arg.as_ptr();
241 self.argv.0.push(ptr::null());
243 // Also make sure we keep track of the owned value to schedule a
244 // destructor for this memory.
248 pub fn cwd(&mut self, dir: &OsStr) {
249 self.cwd = Some(os2c(dir, &mut self.saw_nul));
251 pub fn uid(&mut self, id: uid_t) {
254 pub fn gid(&mut self, id: gid_t) {
257 pub fn groups(&mut self, groups: &[gid_t]) {
258 self.groups = Some(Box::from(groups));
260 pub fn pgroup(&mut self, pgroup: pid_t) {
261 self.pgroup = Some(pgroup);
264 #[cfg(target_os = "linux")]
265 pub fn create_pidfd(&mut self, val: bool) {
266 self.create_pidfd = val;
269 #[cfg(not(target_os = "linux"))]
271 pub fn get_create_pidfd(&self) -> bool {
275 #[cfg(target_os = "linux")]
276 pub fn get_create_pidfd(&self) -> bool {
280 pub fn saw_nul(&self) -> bool {
284 pub fn get_program(&self) -> &OsStr {
285 OsStr::from_bytes(self.program.as_bytes())
289 pub fn get_program_kind(&self) -> ProgramKind {
293 pub fn get_args(&self) -> CommandArgs<'_> {
294 let mut iter = self.args.iter();
299 pub fn get_envs(&self) -> CommandEnvs<'_> {
303 pub fn get_current_dir(&self) -> Option<&Path> {
304 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
307 pub fn get_argv(&self) -> &Vec<*const c_char> {
311 pub fn get_program_cstr(&self) -> &CStr {
316 pub fn get_cwd(&self) -> &Option<CString> {
320 pub fn get_uid(&self) -> Option<uid_t> {
324 pub fn get_gid(&self) -> Option<gid_t> {
328 pub fn get_groups(&self) -> Option<&[gid_t]> {
329 self.groups.as_deref()
332 pub fn get_pgroup(&self) -> Option<pid_t> {
336 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
340 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
341 self.closures.push(f);
344 pub fn stdin(&mut self, stdin: Stdio) {
345 self.stdin = Some(stdin);
348 pub fn stdout(&mut self, stdout: Stdio) {
349 self.stdout = Some(stdout);
352 pub fn stderr(&mut self, stderr: Stdio) {
353 self.stderr = Some(stderr);
356 pub fn env_mut(&mut self) -> &mut CommandEnv {
360 pub fn capture_env(&mut self) -> Option<CStringArray> {
361 let maybe_env = self.env.capture_if_changed();
362 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
366 pub fn env_saw_path(&self) -> bool {
367 self.env.have_changed_path()
371 pub fn program_is_path(&self) -> bool {
372 self.program.to_bytes().contains(&b'/')
379 ) -> io::Result<(StdioPipes, ChildPipes)> {
380 let null = Stdio::Null;
381 let default_stdin = if needs_stdin { &default } else { &null };
382 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
383 let stdout = self.stdout.as_ref().unwrap_or(&default);
384 let stderr = self.stderr.as_ref().unwrap_or(&default);
385 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
386 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
387 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
388 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
389 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
394 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
395 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
397 CString::new("<string-with-nul>").unwrap()
401 // Helper type to manage ownership of the strings within a C-style array.
402 pub struct CStringArray {
404 ptrs: Vec<*const c_char>,
408 pub fn with_capacity(capacity: usize) -> Self {
409 let mut result = CStringArray {
410 items: Vec::with_capacity(capacity),
411 ptrs: Vec::with_capacity(capacity + 1),
413 result.ptrs.push(ptr::null());
416 pub fn push(&mut self, item: CString) {
417 let l = self.ptrs.len();
418 self.ptrs[l - 1] = item.as_ptr();
419 self.ptrs.push(ptr::null());
420 self.items.push(item);
422 pub fn as_ptr(&self) -> *const *const c_char {
427 fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
428 let mut result = CStringArray::with_capacity(env.len());
429 for (mut k, v) in env {
430 // Reserve additional space for '=' and null terminator
431 k.reserve_exact(v.len() + 2);
435 // Add the new entry into the array
436 if let Ok(item) = CString::new(k.into_vec()) {
447 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
449 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
451 // Make sure that the source descriptors are not an stdio
452 // descriptor, otherwise the order which we set the child's
453 // descriptors may blow away a descriptor which we are hoping to
454 // save. For example, suppose we want the child's stderr to be the
455 // parent's stdout, and the child's stdout to be the parent's
456 // stderr. No matter which we dup first, the second will get
457 // overwritten prematurely.
458 Stdio::Fd(ref fd) => {
459 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
460 Ok((ChildStdio::Owned(fd.duplicate()?), None))
462 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
467 let (reader, writer) = pipe::anon_pipe()?;
468 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
469 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
472 #[cfg(not(target_os = "fuchsia"))]
474 let mut opts = OpenOptions::new();
476 opts.write(!readable);
477 let path = unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) };
478 let fd = File::open_c(&path, &opts)?;
479 Ok((ChildStdio::Owned(fd.into_inner()), None))
482 #[cfg(target_os = "fuchsia")]
483 Stdio::Null => Ok((ChildStdio::Null, None)),
488 impl From<AnonPipe> for Stdio {
489 fn from(pipe: AnonPipe) -> Stdio {
490 Stdio::Fd(pipe.into_inner())
494 impl From<File> for Stdio {
495 fn from(file: File) -> Stdio {
496 Stdio::Fd(file.into_inner())
501 pub fn fd(&self) -> Option<c_int> {
503 ChildStdio::Inherit => None,
504 ChildStdio::Explicit(fd) => Some(fd),
505 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
507 #[cfg(target_os = "fuchsia")]
508 ChildStdio::Null => None,
513 impl fmt::Debug for Command {
514 // show all attributes but `self.closures` which does not implement `Debug`
515 // and `self.argv` which is not useful for debugging
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518 let mut debug_command = f.debug_struct("Command");
519 debug_command.field("program", &self.program).field("args", &self.args);
520 if !self.env.is_unchanged() {
521 debug_command.field("env", &self.env);
524 if self.cwd.is_some() {
525 debug_command.field("cwd", &self.cwd);
527 if self.uid.is_some() {
528 debug_command.field("uid", &self.uid);
530 if self.gid.is_some() {
531 debug_command.field("gid", &self.gid);
534 if self.groups.is_some() {
535 debug_command.field("groups", &self.groups);
538 if self.stdin.is_some() {
539 debug_command.field("stdin", &self.stdin);
541 if self.stdout.is_some() {
542 debug_command.field("stdout", &self.stdout);
544 if self.stderr.is_some() {
545 debug_command.field("stderr", &self.stderr);
547 if self.pgroup.is_some() {
548 debug_command.field("pgroup", &self.pgroup);
551 #[cfg(target_os = "linux")]
553 debug_command.field("create_pidfd", &self.create_pidfd);
556 debug_command.finish()
558 if let Some(ref cwd) = self.cwd {
559 write!(f, "cd {cwd:?} && ")?;
561 for (key, value_opt) in self.get_envs() {
562 if let Some(value) = value_opt {
563 write!(f, "{}={value:?} ", key.to_string_lossy())?;
566 if self.program != self.args[0] {
567 write!(f, "[{:?}] ", self.program)?;
569 write!(f, "{:?}", self.args[0])?;
571 for arg in &self.args[1..] {
572 write!(f, " {:?}", arg)?;
579 #[derive(PartialEq, Eq, Clone, Copy)]
580 pub struct ExitCode(u8);
582 impl fmt::Debug for ExitCode {
583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584 f.debug_tuple("unix_exit_status").field(&self.0).finish()
589 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
590 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
593 pub fn as_i32(&self) -> i32 {
598 impl From<u8> for ExitCode {
599 fn from(code: u8) -> Self {
604 pub struct CommandArgs<'a> {
605 iter: crate::slice::Iter<'a, CString>,
608 impl<'a> Iterator for CommandArgs<'a> {
609 type Item = &'a OsStr;
610 fn next(&mut self) -> Option<&'a OsStr> {
611 self.iter.next().map(|cs| OsStr::from_bytes(cs.as_bytes()))
613 fn size_hint(&self) -> (usize, Option<usize>) {
614 self.iter.size_hint()
618 impl<'a> ExactSizeIterator for CommandArgs<'a> {
619 fn len(&self) -> usize {
622 fn is_empty(&self) -> bool {
627 impl<'a> fmt::Debug for CommandArgs<'a> {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.debug_list().entries(self.iter.clone()).finish()