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")]
154 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
155 pub enum ProgramKind {
156 /// A program that would be looked up on the PATH (e.g. `ls`)
158 /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
160 /// An absolute path.
165 fn new(program: &OsStr) -> Self {
166 if program.bytes().starts_with(b"/") {
168 } else if program.bytes().contains(&b'/') {
169 // If the program has more than one component in it, it is a relative path.
178 #[cfg(not(target_os = "linux"))]
179 pub fn new(program: &OsStr) -> Command {
180 let mut saw_nul = false;
181 let program_kind = ProgramKind::new(program.as_ref());
182 let program = os2c(program, &mut saw_nul);
184 argv: Argv(vec![program.as_ptr(), ptr::null()]),
185 args: vec![program.clone()],
188 env: Default::default(),
193 closures: Vec::new(),
202 #[cfg(target_os = "linux")]
203 pub fn new(program: &OsStr) -> Command {
204 let mut saw_nul = false;
205 let program_kind = ProgramKind::new(program.as_ref());
206 let program = os2c(program, &mut saw_nul);
208 argv: Argv(vec![program.as_ptr(), ptr::null()]),
209 args: vec![program.clone()],
212 env: Default::default(),
217 closures: Vec::new(),
227 pub fn set_arg_0(&mut self, arg: &OsStr) {
229 let arg = os2c(arg, &mut self.saw_nul);
230 debug_assert!(self.argv.0.len() > 1);
231 self.argv.0[0] = arg.as_ptr();
235 pub fn arg(&mut self, arg: &OsStr) {
236 // Overwrite the trailing null pointer in `argv` and then add a new null
238 let arg = os2c(arg, &mut self.saw_nul);
239 self.argv.0[self.args.len()] = arg.as_ptr();
240 self.argv.0.push(ptr::null());
242 // Also make sure we keep track of the owned value to schedule a
243 // destructor for this memory.
247 pub fn cwd(&mut self, dir: &OsStr) {
248 self.cwd = Some(os2c(dir, &mut self.saw_nul));
250 pub fn uid(&mut self, id: uid_t) {
253 pub fn gid(&mut self, id: gid_t) {
256 pub fn groups(&mut self, groups: &[gid_t]) {
257 self.groups = Some(Box::from(groups));
259 pub fn pgroup(&mut self, pgroup: pid_t) {
260 self.pgroup = Some(pgroup);
263 #[cfg(target_os = "linux")]
264 pub fn create_pidfd(&mut self, val: bool) {
265 self.create_pidfd = val;
268 #[cfg(not(target_os = "linux"))]
270 pub fn get_create_pidfd(&self) -> bool {
274 #[cfg(target_os = "linux")]
275 pub fn get_create_pidfd(&self) -> bool {
279 pub fn saw_nul(&self) -> bool {
283 pub fn get_program(&self) -> &OsStr {
284 OsStr::from_bytes(self.program.as_bytes())
288 pub fn get_program_kind(&self) -> ProgramKind {
292 pub fn get_args(&self) -> CommandArgs<'_> {
293 let mut iter = self.args.iter();
298 pub fn get_envs(&self) -> CommandEnvs<'_> {
302 pub fn get_current_dir(&self) -> Option<&Path> {
303 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
306 pub fn get_argv(&self) -> &Vec<*const c_char> {
310 pub fn get_program_cstr(&self) -> &CStr {
315 pub fn get_cwd(&self) -> &Option<CString> {
319 pub fn get_uid(&self) -> Option<uid_t> {
323 pub fn get_gid(&self) -> Option<gid_t> {
327 pub fn get_groups(&self) -> Option<&[gid_t]> {
328 self.groups.as_deref()
331 pub fn get_pgroup(&self) -> Option<pid_t> {
335 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
339 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
340 self.closures.push(f);
343 pub fn stdin(&mut self, stdin: Stdio) {
344 self.stdin = Some(stdin);
347 pub fn stdout(&mut self, stdout: Stdio) {
348 self.stdout = Some(stdout);
351 pub fn stderr(&mut self, stderr: Stdio) {
352 self.stderr = Some(stderr);
355 pub fn env_mut(&mut self) -> &mut CommandEnv {
359 pub fn capture_env(&mut self) -> Option<CStringArray> {
360 let maybe_env = self.env.capture_if_changed();
361 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
365 pub fn env_saw_path(&self) -> bool {
366 self.env.have_changed_path()
370 pub fn program_is_path(&self) -> bool {
371 self.program.to_bytes().contains(&b'/')
378 ) -> io::Result<(StdioPipes, ChildPipes)> {
379 let null = Stdio::Null;
380 let default_stdin = if needs_stdin { &default } else { &null };
381 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
382 let stdout = self.stdout.as_ref().unwrap_or(&default);
383 let stderr = self.stderr.as_ref().unwrap_or(&default);
384 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
385 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
386 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
387 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
388 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
393 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
394 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
396 CString::new("<string-with-nul>").unwrap()
400 // Helper type to manage ownership of the strings within a C-style array.
401 pub struct CStringArray {
403 ptrs: Vec<*const c_char>,
407 pub fn with_capacity(capacity: usize) -> Self {
408 let mut result = CStringArray {
409 items: Vec::with_capacity(capacity),
410 ptrs: Vec::with_capacity(capacity + 1),
412 result.ptrs.push(ptr::null());
415 pub fn push(&mut self, item: CString) {
416 let l = self.ptrs.len();
417 self.ptrs[l - 1] = item.as_ptr();
418 self.ptrs.push(ptr::null());
419 self.items.push(item);
421 pub fn as_ptr(&self) -> *const *const c_char {
426 fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
427 let mut result = CStringArray::with_capacity(env.len());
428 for (mut k, v) in env {
429 // Reserve additional space for '=' and null terminator
430 k.reserve_exact(v.len() + 2);
434 // Add the new entry into the array
435 if let Ok(item) = CString::new(k.into_vec()) {
446 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
448 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
450 // Make sure that the source descriptors are not an stdio
451 // descriptor, otherwise the order which we set the child's
452 // descriptors may blow away a descriptor which we are hoping to
453 // save. For example, suppose we want the child's stderr to be the
454 // parent's stdout, and the child's stdout to be the parent's
455 // stderr. No matter which we dup first, the second will get
456 // overwritten prematurely.
457 Stdio::Fd(ref fd) => {
458 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
459 Ok((ChildStdio::Owned(fd.duplicate()?), None))
461 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
466 let (reader, writer) = pipe::anon_pipe()?;
467 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
468 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
471 #[cfg(not(target_os = "fuchsia"))]
473 let mut opts = OpenOptions::new();
475 opts.write(!readable);
476 let path = unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) };
477 let fd = File::open_c(&path, &opts)?;
478 Ok((ChildStdio::Owned(fd.into_inner()), None))
481 #[cfg(target_os = "fuchsia")]
482 Stdio::Null => Ok((ChildStdio::Null, None)),
487 impl From<AnonPipe> for Stdio {
488 fn from(pipe: AnonPipe) -> Stdio {
489 Stdio::Fd(pipe.into_inner())
493 impl From<File> for Stdio {
494 fn from(file: File) -> Stdio {
495 Stdio::Fd(file.into_inner())
500 pub fn fd(&self) -> Option<c_int> {
502 ChildStdio::Inherit => None,
503 ChildStdio::Explicit(fd) => Some(fd),
504 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
506 #[cfg(target_os = "fuchsia")]
507 ChildStdio::Null => None,
512 impl fmt::Debug for Command {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 if self.program != self.args[0] {
515 write!(f, "[{:?}] ", self.program)?;
517 write!(f, "{:?}", self.args[0])?;
519 for arg in &self.args[1..] {
520 write!(f, " {:?}", arg)?;
526 #[derive(PartialEq, Eq, Clone, Copy)]
527 pub struct ExitCode(u8);
529 impl fmt::Debug for ExitCode {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 f.debug_tuple("unix_exit_status").field(&self.0).finish()
536 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
537 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
540 pub fn as_i32(&self) -> i32 {
545 impl From<u8> for ExitCode {
546 fn from(code: u8) -> Self {
551 pub struct CommandArgs<'a> {
552 iter: crate::slice::Iter<'a, CString>,
555 impl<'a> Iterator for CommandArgs<'a> {
556 type Item = &'a OsStr;
557 fn next(&mut self) -> Option<&'a OsStr> {
558 self.iter.next().map(|cs| OsStr::from_bytes(cs.as_bytes()))
560 fn size_hint(&self) -> (usize, Option<usize>) {
561 self.iter.size_hint()
565 impl<'a> ExactSizeIterator for CommandArgs<'a> {
566 fn len(&self) -> usize {
569 fn is_empty(&self) -> bool {
574 impl<'a> fmt::Debug for CommandArgs<'a> {
575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576 f.debug_list().entries(self.iter.clone()).finish()