1 #[cfg(all(test, not(target_os = "emscripten")))]
2 mod tests;
3
4 use crate::os::unix::prelude::*;
5
6 use crate::collections::BTreeMap;
7 use crate::ffi::{CStr, CString, OsStr, OsString};
8 use crate::fmt;
9 use crate::io;
10 use crate::path::Path;
11 use crate::ptr;
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;
17
18 #[cfg(not(target_os = "fuchsia"))]
19 use crate::sys::fs::OpenOptions;
20
21 use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS};
22
23 cfg_if::cfg_if! {
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";
30 } else {
31 const DEV_NULL: &str = "/dev/null\0";
32 }
33 }
34
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
40 cfg_if::cfg_if! {
41 if #[cfg(target_os = "android")] {
42 #[allow(dead_code)]
43 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
44 set.write_bytes(0u8, 1);
45 return 0;
46 }
47
48 #[allow(dead_code)]
49 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
50 use crate::{
51 mem::{align_of, size_of},
52 slice,
53 };
54 use libc::{c_ulong, sigset_t};
55
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
62 );
63
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);
67 return -1;
68 }
69 let raw = slice::from_raw_parts_mut(
70 set as *mut c_ulong,
71 size_of::<sigset_t>() / size_of::<c_ulong>(),
72 );
73 const LONG_BIT: usize = size_of::<c_ulong>() * 8;
74 raw[bit / LONG_BIT] |= 1 << (bit % LONG_BIT);
75 return 0;
76 }
77 } else {
78 pub use libc::{sigemptyset, sigaddset};
79 }
80 }
81
82 ////////////////////////////////////////////////////////////////////////////////
83 // Command
84 ////////////////////////////////////////////////////////////////////////////////
85
86 pub struct Command {
87 program: CString,
88 args: Vec<CString>,
89 /// Exactly what will be passed to `execvp`.
90 ///
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.
94 argv: Argv,
95 env: CommandEnv,
96
97 program_kind: ProgramKind,
98 cwd: Option<CString>,
99 uid: Option<uid_t>,
100 gid: Option<gid_t>,
101 saw_nul: bool,
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")]
108 create_pidfd: bool,
109 pgroup: Option<pid_t>,
110 }
111
112 // Create a new type for argv, so that we can make it `Send` and `Sync`
113 struct Argv(Vec<*const c_char>);
114
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 {}
119
120 // passed back to std::process with the pipes connected to the child, if any
121 // were requested
122 pub struct StdioPipes {
123 pub stdin: Option<AnonPipe>,
124 pub stdout: Option<AnonPipe>,
125 pub stderr: Option<AnonPipe>,
126 }
127
128 // passed to do_exec() with configuration of what the child stdio should look
129 // like
130 pub struct ChildPipes {
131 pub stdin: ChildStdio,
132 pub stdout: ChildStdio,
133 pub stderr: ChildStdio,
134 }
135
136 pub enum ChildStdio {
137 Inherit,
138 Explicit(c_int),
139 Owned(FileDesc),
140
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")]
144 Null,
145 }
146
147 #[derive(Debug)]
148 pub enum Stdio {
149 Inherit,
150 Null,
151 MakePipe,
152 Fd(FileDesc),
153 }
154
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`)
158 PathLookup,
159 /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
160 Relative,
161 /// An absolute path.
162 Absolute,
163 }
164
165 impl ProgramKind {
new(program: &OsStr) -> Self166 fn new(program: &OsStr) -> Self {
167 if program.as_os_str_bytes().starts_with(b"/") {
168 Self::Absolute
169 } else if program.as_os_str_bytes().contains(&b'/') {
170 // If the program has more than one component in it, it is a relative path.
171 Self::Relative
172 } else {
173 Self::PathLookup
174 }
175 }
176 }
177
178 impl Command {
179 #[cfg(not(target_os = "linux"))]
new(program: &OsStr) -> Command180 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);
184 Command {
185 argv: Argv(vec![program.as_ptr(), ptr::null()]),
186 args: vec![program.clone()],
187 program,
188 program_kind,
189 env: Default::default(),
190 cwd: None,
191 uid: None,
192 gid: None,
193 saw_nul,
194 closures: Vec::new(),
195 groups: None,
196 stdin: None,
197 stdout: None,
198 stderr: None,
199 pgroup: None,
200 }
201 }
202
203 #[cfg(target_os = "linux")]
new(program: &OsStr) -> Command204 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);
208 Command {
209 argv: Argv(vec![program.as_ptr(), ptr::null()]),
210 args: vec![program.clone()],
211 program,
212 program_kind,
213 env: Default::default(),
214 cwd: None,
215 uid: None,
216 gid: None,
217 saw_nul,
218 closures: Vec::new(),
219 groups: None,
220 stdin: None,
221 stdout: None,
222 stderr: None,
223 create_pidfd: false,
224 pgroup: None,
225 }
226 }
227
set_arg_0(&mut self, arg: &OsStr)228 pub fn set_arg_0(&mut self, arg: &OsStr) {
229 // Set a new arg0
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();
233 self.args[0] = arg;
234 }
235
arg(&mut self, arg: &OsStr)236 pub fn arg(&mut self, arg: &OsStr) {
237 // Overwrite the trailing null pointer in `argv` and then add a new null
238 // pointer.
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());
242
243 // Also make sure we keep track of the owned value to schedule a
244 // destructor for this memory.
245 self.args.push(arg);
246 }
247
cwd(&mut self, dir: &OsStr)248 pub fn cwd(&mut self, dir: &OsStr) {
249 self.cwd = Some(os2c(dir, &mut self.saw_nul));
250 }
uid(&mut self, id: uid_t)251 pub fn uid(&mut self, id: uid_t) {
252 self.uid = Some(id);
253 }
gid(&mut self, id: gid_t)254 pub fn gid(&mut self, id: gid_t) {
255 self.gid = Some(id);
256 }
groups(&mut self, groups: &[gid_t])257 pub fn groups(&mut self, groups: &[gid_t]) {
258 self.groups = Some(Box::from(groups));
259 }
pgroup(&mut self, pgroup: pid_t)260 pub fn pgroup(&mut self, pgroup: pid_t) {
261 self.pgroup = Some(pgroup);
262 }
263
264 #[cfg(target_os = "linux")]
create_pidfd(&mut self, val: bool)265 pub fn create_pidfd(&mut self, val: bool) {
266 self.create_pidfd = val;
267 }
268
269 #[cfg(not(target_os = "linux"))]
270 #[allow(dead_code)]
get_create_pidfd(&self) -> bool271 pub fn get_create_pidfd(&self) -> bool {
272 false
273 }
274
275 #[cfg(target_os = "linux")]
get_create_pidfd(&self) -> bool276 pub fn get_create_pidfd(&self) -> bool {
277 self.create_pidfd
278 }
279
saw_nul(&self) -> bool280 pub fn saw_nul(&self) -> bool {
281 self.saw_nul
282 }
283
get_program(&self) -> &OsStr284 pub fn get_program(&self) -> &OsStr {
285 OsStr::from_bytes(self.program.as_bytes())
286 }
287
288 #[allow(dead_code)]
get_program_kind(&self) -> ProgramKind289 pub fn get_program_kind(&self) -> ProgramKind {
290 self.program_kind
291 }
292
get_args(&self) -> CommandArgs<'_>293 pub fn get_args(&self) -> CommandArgs<'_> {
294 let mut iter = self.args.iter();
295 iter.next();
296 CommandArgs { iter }
297 }
298
get_envs(&self) -> CommandEnvs<'_>299 pub fn get_envs(&self) -> CommandEnvs<'_> {
300 self.env.iter()
301 }
302
get_current_dir(&self) -> Option<&Path>303 pub fn get_current_dir(&self) -> Option<&Path> {
304 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
305 }
306
get_argv(&self) -> &Vec<*const c_char>307 pub fn get_argv(&self) -> &Vec<*const c_char> {
308 &self.argv.0
309 }
310
get_program_cstr(&self) -> &CStr311 pub fn get_program_cstr(&self) -> &CStr {
312 &*self.program
313 }
314
315 #[allow(dead_code)]
get_cwd(&self) -> &Option<CString>316 pub fn get_cwd(&self) -> &Option<CString> {
317 &self.cwd
318 }
319 #[allow(dead_code)]
get_uid(&self) -> Option<uid_t>320 pub fn get_uid(&self) -> Option<uid_t> {
321 self.uid
322 }
323 #[allow(dead_code)]
get_gid(&self) -> Option<gid_t>324 pub fn get_gid(&self) -> Option<gid_t> {
325 self.gid
326 }
327 #[allow(dead_code)]
get_groups(&self) -> Option<&[gid_t]>328 pub fn get_groups(&self) -> Option<&[gid_t]> {
329 self.groups.as_deref()
330 }
331 #[allow(dead_code)]
get_pgroup(&self) -> Option<pid_t>332 pub fn get_pgroup(&self) -> Option<pid_t> {
333 self.pgroup
334 }
335
get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>336 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
337 &mut self.closures
338 }
339
pre_exec(&mut self, f: 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);
342 }
343
stdin(&mut self, stdin: Stdio)344 pub fn stdin(&mut self, stdin: Stdio) {
345 self.stdin = Some(stdin);
346 }
347
stdout(&mut self, stdout: Stdio)348 pub fn stdout(&mut self, stdout: Stdio) {
349 self.stdout = Some(stdout);
350 }
351
stderr(&mut self, stderr: Stdio)352 pub fn stderr(&mut self, stderr: Stdio) {
353 self.stderr = Some(stderr);
354 }
355
env_mut(&mut self) -> &mut CommandEnv356 pub fn env_mut(&mut self) -> &mut CommandEnv {
357 &mut self.env
358 }
359
capture_env(&mut self) -> Option<CStringArray>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))
363 }
364
365 #[allow(dead_code)]
env_saw_path(&self) -> bool366 pub fn env_saw_path(&self) -> bool {
367 self.env.have_changed_path()
368 }
369
370 #[allow(dead_code)]
program_is_path(&self) -> bool371 pub fn program_is_path(&self) -> bool {
372 self.program.to_bytes().contains(&b'/')
373 }
374
setup_io( &self, default: Stdio, needs_stdin: bool, ) -> io::Result<(StdioPipes, ChildPipes)>375 pub fn setup_io(
376 &self,
377 default: Stdio,
378 needs_stdin: bool,
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 };
390 Ok((ours, theirs))
391 }
392 }
393
os2c(s: &OsStr, saw_nul: &mut bool) -> CString394 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
395 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
396 *saw_nul = true;
397 CString::new("<string-with-nul>").unwrap()
398 })
399 }
400
401 // Helper type to manage ownership of the strings within a C-style array.
402 pub struct CStringArray {
403 items: Vec<CString>,
404 ptrs: Vec<*const c_char>,
405 }
406
407 impl CStringArray {
with_capacity(capacity: usize) -> Self408 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),
412 };
413 result.ptrs.push(ptr::null());
414 result
415 }
push(&mut self, item: CString)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);
421 }
as_ptr(&self) -> *const *const c_char422 pub fn as_ptr(&self) -> *const *const c_char {
423 self.ptrs.as_ptr()
424 }
425 }
426
construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray427 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);
432 k.push("=");
433 k.push(&v);
434
435 // Add the new entry into the array
436 if let Ok(item) = CString::new(k.into_vec()) {
437 result.push(item);
438 } else {
439 *saw_nul = true;
440 }
441 }
442
443 result
444 }
445
446 impl Stdio {
to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)>447 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
448 match *self {
449 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
450
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))
461 } else {
462 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
463 }
464 }
465
466 Stdio::MakePipe => {
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)))
470 }
471
472 #[cfg(not(target_os = "fuchsia"))]
473 Stdio::Null => {
474 let mut opts = OpenOptions::new();
475 opts.read(readable);
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))
480 }
481
482 #[cfg(target_os = "fuchsia")]
483 Stdio::Null => Ok((ChildStdio::Null, None)),
484 }
485 }
486 }
487
488 impl From<AnonPipe> for Stdio {
from(pipe: AnonPipe) -> Stdio489 fn from(pipe: AnonPipe) -> Stdio {
490 Stdio::Fd(pipe.into_inner())
491 }
492 }
493
494 impl From<File> for Stdio {
from(file: File) -> Stdio495 fn from(file: File) -> Stdio {
496 Stdio::Fd(file.into_inner())
497 }
498 }
499
500 impl ChildStdio {
fd(&self) -> Option<c_int>501 pub fn fd(&self) -> Option<c_int> {
502 match *self {
503 ChildStdio::Inherit => None,
504 ChildStdio::Explicit(fd) => Some(fd),
505 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
506
507 #[cfg(target_os = "fuchsia")]
508 ChildStdio::Null => None,
509 }
510 }
511 }
512
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
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 if f.alternate() {
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);
522 }
523
524 if self.cwd.is_some() {
525 debug_command.field("cwd", &self.cwd);
526 }
527 if self.uid.is_some() {
528 debug_command.field("uid", &self.uid);
529 }
530 if self.gid.is_some() {
531 debug_command.field("gid", &self.gid);
532 }
533
534 if self.groups.is_some() {
535 debug_command.field("groups", &self.groups);
536 }
537
538 if self.stdin.is_some() {
539 debug_command.field("stdin", &self.stdin);
540 }
541 if self.stdout.is_some() {
542 debug_command.field("stdout", &self.stdout);
543 }
544 if self.stderr.is_some() {
545 debug_command.field("stderr", &self.stderr);
546 }
547 if self.pgroup.is_some() {
548 debug_command.field("pgroup", &self.pgroup);
549 }
550
551 #[cfg(target_os = "linux")]
552 {
553 debug_command.field("create_pidfd", &self.create_pidfd);
554 }
555
556 debug_command.finish()
557 } else {
558 if let Some(ref cwd) = self.cwd {
559 write!(f, "cd {cwd:?} && ")?;
560 }
561 for (key, value_opt) in self.get_envs() {
562 if let Some(value) = value_opt {
563 write!(f, "{}={value:?} ", key.to_string_lossy())?;
564 }
565 }
566 if self.program != self.args[0] {
567 write!(f, "[{:?}] ", self.program)?;
568 }
569 write!(f, "{:?}", self.args[0])?;
570
571 for arg in &self.args[1..] {
572 write!(f, " {:?}", arg)?;
573 }
574 Ok(())
575 }
576 }
577 }
578
579 #[derive(PartialEq, Eq, Clone, Copy)]
580 pub struct ExitCode(u8);
581
582 impl fmt::Debug for ExitCode {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584 f.debug_tuple("unix_exit_status").field(&self.0).finish()
585 }
586 }
587
588 impl ExitCode {
589 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
590 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
591
592 #[inline]
as_i32(&self) -> i32593 pub fn as_i32(&self) -> i32 {
594 self.0 as i32
595 }
596 }
597
598 impl From<u8> for ExitCode {
from(code: u8) -> Self599 fn from(code: u8) -> Self {
600 Self(code)
601 }
602 }
603
604 pub struct CommandArgs<'a> {
605 iter: crate::slice::Iter<'a, CString>,
606 }
607
608 impl<'a> Iterator for CommandArgs<'a> {
609 type Item = &'a OsStr;
next(&mut self) -> Option<&'a OsStr>610 fn next(&mut self) -> Option<&'a OsStr> {
611 self.iter.next().map(|cs| OsStr::from_bytes(cs.as_bytes()))
612 }
size_hint(&self) -> (usize, Option<usize>)613 fn size_hint(&self) -> (usize, Option<usize>) {
614 self.iter.size_hint()
615 }
616 }
617
618 impl<'a> ExactSizeIterator for CommandArgs<'a> {
len(&self) -> usize619 fn len(&self) -> usize {
620 self.iter.len()
621 }
is_empty(&self) -> bool622 fn is_empty(&self) -> bool {
623 self.iter.is_empty()
624 }
625 }
626
627 impl<'a> fmt::Debug for CommandArgs<'a> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.debug_list().entries(self.iter.clone()).finish()
630 }
631 }
632