1#[cfg(all(test, not(target_os = "emscripten")))]
2mod tests;
3
4use crate::os::unix::prelude::*;
5
6use crate::collections::BTreeMap;
7use crate::ffi::{CStr, CString, OsStr, OsString};
8use crate::fmt;
9use crate::io;
10use crate::path::Path;
11use crate::ptr;
12use crate::sys::fd::FileDesc;
13use crate::sys::fs::File;
14use crate::sys::pipe::{self, AnonPipe};
15use crate::sys_common::process::{CommandEnv, CommandEnvs};
16use crate::sys_common::{FromInner, IntoInner};
17
18#[cfg(not(target_os = "fuchsia"))]
19use crate::sys::fs::OpenOptions;
20
21use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS};
22
23cfg_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: &CStr = c"null:";
28 } else if #[cfg(target_os = "vxworks")] {
29 const DEV_NULL: &CStr = c"/null";
30 } else {
31 const DEV_NULL: &CStr = c"/dev/null";
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
40cfg_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::pal::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 #[allow(unused_imports)]
79 pub use libc::{sigemptyset, sigaddset};
80 }
81}
82
83////////////////////////////////////////////////////////////////////////////////
84// Command
85////////////////////////////////////////////////////////////////////////////////
86
87pub struct Command {
88 program: CString,
89 args: Vec<CString>,
90 /// Exactly what will be passed to `execvp`.
91 ///
92 /// First element is a pointer to `program`, followed by pointers to
93 /// `args`, followed by a `null`. Be careful when modifying `program` or
94 /// `args` to properly update this as well.
95 argv: Argv,
96 env: CommandEnv,
97
98 program_kind: ProgramKind,
99 cwd: Option<CString>,
100 uid: Option<uid_t>,
101 gid: Option<gid_t>,
102 saw_nul: bool,
103 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
104 groups: Option<Box<[gid_t]>>,
105 stdin: Option<Stdio>,
106 stdout: Option<Stdio>,
107 stderr: Option<Stdio>,
108 #[cfg(target_os = "linux")]
109 create_pidfd: bool,
110 pgroup: Option<pid_t>,
111}
112
113// Create a new type for argv, so that we can make it `Send` and `Sync`
114struct Argv(Vec<*const c_char>);
115
116// It is safe to make `Argv` `Send` and `Sync`, because it contains
117// pointers to memory owned by `Command.args`
118unsafe impl Send for Argv {}
119unsafe impl Sync for Argv {}
120
121// passed back to std::process with the pipes connected to the child, if any
122// were requested
123pub struct StdioPipes {
124 pub stdin: Option<AnonPipe>,
125 pub stdout: Option<AnonPipe>,
126 pub stderr: Option<AnonPipe>,
127}
128
129// passed to do_exec() with configuration of what the child stdio should look
130// like
131pub struct ChildPipes {
132 pub stdin: ChildStdio,
133 pub stdout: ChildStdio,
134 pub stderr: ChildStdio,
135}
136
137pub enum ChildStdio {
138 Inherit,
139 Explicit(c_int),
140 Owned(FileDesc),
141
142 // On Fuchsia, null stdio is the default, so we simply don't specify
143 // any actions at the time of spawning.
144 #[cfg(target_os = "fuchsia")]
145 Null,
146}
147
148#[derive(Debug)]
149pub enum Stdio {
150 Inherit,
151 Null,
152 MakePipe,
153 Fd(FileDesc),
154 StaticFd(BorrowedFd<'static>),
155}
156
157#[derive(Copy, Clone, Debug, Eq, PartialEq)]
158pub enum ProgramKind {
159 /// A program that would be looked up on the PATH (e.g. `ls`)
160 PathLookup,
161 /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
162 Relative,
163 /// An absolute path.
164 Absolute,
165}
166
167impl ProgramKind {
168 fn new(program: &OsStr) -> Self {
169 if program.as_encoded_bytes().starts_with(needle:b"/") {
170 Self::Absolute
171 } else if program.as_encoded_bytes().contains(&b'/') {
172 // If the program has more than one component in it, it is a relative path.
173 Self::Relative
174 } else {
175 Self::PathLookup
176 }
177 }
178}
179
180impl Command {
181 #[cfg(not(target_os = "linux"))]
182 pub fn new(program: &OsStr) -> Command {
183 let mut saw_nul = false;
184 let program_kind = ProgramKind::new(program.as_ref());
185 let program = os2c(program, &mut saw_nul);
186 Command {
187 argv: Argv(vec![program.as_ptr(), ptr::null()]),
188 args: vec![program.clone()],
189 program,
190 program_kind,
191 env: Default::default(),
192 cwd: None,
193 uid: None,
194 gid: None,
195 saw_nul,
196 closures: Vec::new(),
197 groups: None,
198 stdin: None,
199 stdout: None,
200 stderr: None,
201 pgroup: None,
202 }
203 }
204
205 #[cfg(target_os = "linux")]
206 pub fn new(program: &OsStr) -> Command {
207 let mut saw_nul = false;
208 let program_kind = ProgramKind::new(program.as_ref());
209 let program = os2c(program, &mut saw_nul);
210 Command {
211 argv: Argv(vec![program.as_ptr(), ptr::null()]),
212 args: vec![program.clone()],
213 program,
214 program_kind,
215 env: Default::default(),
216 cwd: None,
217 uid: None,
218 gid: None,
219 saw_nul,
220 closures: Vec::new(),
221 groups: None,
222 stdin: None,
223 stdout: None,
224 stderr: None,
225 create_pidfd: false,
226 pgroup: None,
227 }
228 }
229
230 pub fn set_arg_0(&mut self, arg: &OsStr) {
231 // Set a new arg0
232 let arg = os2c(arg, &mut self.saw_nul);
233 debug_assert!(self.argv.0.len() > 1);
234 self.argv.0[0] = arg.as_ptr();
235 self.args[0] = arg;
236 }
237
238 pub fn arg(&mut self, arg: &OsStr) {
239 // Overwrite the trailing null pointer in `argv` and then add a new null
240 // pointer.
241 let arg = os2c(arg, &mut self.saw_nul);
242 self.argv.0[self.args.len()] = arg.as_ptr();
243 self.argv.0.push(ptr::null());
244
245 // Also make sure we keep track of the owned value to schedule a
246 // destructor for this memory.
247 self.args.push(arg);
248 }
249
250 pub fn cwd(&mut self, dir: &OsStr) {
251 self.cwd = Some(os2c(dir, &mut self.saw_nul));
252 }
253 pub fn uid(&mut self, id: uid_t) {
254 self.uid = Some(id);
255 }
256 pub fn gid(&mut self, id: gid_t) {
257 self.gid = Some(id);
258 }
259 pub fn groups(&mut self, groups: &[gid_t]) {
260 self.groups = Some(Box::from(groups));
261 }
262 pub fn pgroup(&mut self, pgroup: pid_t) {
263 self.pgroup = Some(pgroup);
264 }
265
266 #[cfg(target_os = "linux")]
267 pub fn create_pidfd(&mut self, val: bool) {
268 self.create_pidfd = val;
269 }
270
271 #[cfg(not(target_os = "linux"))]
272 #[allow(dead_code)]
273 pub fn get_create_pidfd(&self) -> bool {
274 false
275 }
276
277 #[cfg(target_os = "linux")]
278 pub fn get_create_pidfd(&self) -> bool {
279 self.create_pidfd
280 }
281
282 pub fn saw_nul(&self) -> bool {
283 self.saw_nul
284 }
285
286 pub fn get_program(&self) -> &OsStr {
287 OsStr::from_bytes(self.program.as_bytes())
288 }
289
290 #[allow(dead_code)]
291 pub fn get_program_kind(&self) -> ProgramKind {
292 self.program_kind
293 }
294
295 pub fn get_args(&self) -> CommandArgs<'_> {
296 let mut iter = self.args.iter();
297 iter.next();
298 CommandArgs { iter }
299 }
300
301 pub fn get_envs(&self) -> CommandEnvs<'_> {
302 self.env.iter()
303 }
304
305 pub fn get_current_dir(&self) -> Option<&Path> {
306 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
307 }
308
309 pub fn get_argv(&self) -> &Vec<*const c_char> {
310 &self.argv.0
311 }
312
313 pub fn get_program_cstr(&self) -> &CStr {
314 &*self.program
315 }
316
317 #[allow(dead_code)]
318 pub fn get_cwd(&self) -> &Option<CString> {
319 &self.cwd
320 }
321 #[allow(dead_code)]
322 pub fn get_uid(&self) -> Option<uid_t> {
323 self.uid
324 }
325 #[allow(dead_code)]
326 pub fn get_gid(&self) -> Option<gid_t> {
327 self.gid
328 }
329 #[allow(dead_code)]
330 pub fn get_groups(&self) -> Option<&[gid_t]> {
331 self.groups.as_deref()
332 }
333 #[allow(dead_code)]
334 pub fn get_pgroup(&self) -> Option<pid_t> {
335 self.pgroup
336 }
337
338 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
339 &mut self.closures
340 }
341
342 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
343 self.closures.push(f);
344 }
345
346 pub fn stdin(&mut self, stdin: Stdio) {
347 self.stdin = Some(stdin);
348 }
349
350 pub fn stdout(&mut self, stdout: Stdio) {
351 self.stdout = Some(stdout);
352 }
353
354 pub fn stderr(&mut self, stderr: Stdio) {
355 self.stderr = Some(stderr);
356 }
357
358 pub fn env_mut(&mut self) -> &mut CommandEnv {
359 &mut self.env
360 }
361
362 pub fn capture_env(&mut self) -> Option<CStringArray> {
363 let maybe_env = self.env.capture_if_changed();
364 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
365 }
366
367 #[allow(dead_code)]
368 pub fn env_saw_path(&self) -> bool {
369 self.env.have_changed_path()
370 }
371
372 #[allow(dead_code)]
373 pub fn program_is_path(&self) -> bool {
374 self.program.to_bytes().contains(&b'/')
375 }
376
377 pub fn setup_io(
378 &self,
379 default: Stdio,
380 needs_stdin: bool,
381 ) -> io::Result<(StdioPipes, ChildPipes)> {
382 let null = Stdio::Null;
383 let default_stdin = if needs_stdin { &default } else { &null };
384 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
385 let stdout = self.stdout.as_ref().unwrap_or(&default);
386 let stderr = self.stderr.as_ref().unwrap_or(&default);
387 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
388 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
389 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
390 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
391 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
392 Ok((ours, theirs))
393 }
394}
395
396fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
397 CString::new(s.as_bytes()).unwrap_or_else(|_e: NulError| {
398 *saw_nul = true;
399 CString::new("<string-with-nul>").unwrap()
400 })
401}
402
403// Helper type to manage ownership of the strings within a C-style array.
404pub struct CStringArray {
405 items: Vec<CString>,
406 ptrs: Vec<*const c_char>,
407}
408
409impl CStringArray {
410 pub fn with_capacity(capacity: usize) -> Self {
411 let mut result: CStringArray = CStringArray {
412 items: Vec::with_capacity(capacity),
413 ptrs: Vec::with_capacity(capacity + 1),
414 };
415 result.ptrs.push(ptr::null());
416 result
417 }
418 pub fn push(&mut self, item: CString) {
419 let l: usize = self.ptrs.len();
420 self.ptrs[l - 1] = item.as_ptr();
421 self.ptrs.push(ptr::null());
422 self.items.push(item);
423 }
424 pub fn as_ptr(&self) -> *const *const c_char {
425 self.ptrs.as_ptr()
426 }
427}
428
429fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
430 let mut result: CStringArray = CStringArray::with_capacity(env.len());
431 for (mut k: OsString, v: OsString) in env {
432 // Reserve additional space for '=' and null terminator
433 k.reserve_exact(additional:v.len() + 2);
434 k.push("=");
435 k.push(&v);
436
437 // Add the new entry into the array
438 if let Ok(item: CString) = CString::new(k.into_vec()) {
439 result.push(item);
440 } else {
441 *saw_nul = true;
442 }
443 }
444
445 result
446}
447
448impl Stdio {
449 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
450 match *self {
451 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
452
453 // Make sure that the source descriptors are not an stdio
454 // descriptor, otherwise the order which we set the child's
455 // descriptors may blow away a descriptor which we are hoping to
456 // save. For example, suppose we want the child's stderr to be the
457 // parent's stdout, and the child's stdout to be the parent's
458 // stderr. No matter which we dup first, the second will get
459 // overwritten prematurely.
460 Stdio::Fd(ref fd) => {
461 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
462 Ok((ChildStdio::Owned(fd.duplicate()?), None))
463 } else {
464 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
465 }
466 }
467
468 Stdio::StaticFd(fd) => {
469 let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
470 Ok((ChildStdio::Owned(fd), None))
471 }
472
473 Stdio::MakePipe => {
474 let (reader, writer) = pipe::anon_pipe()?;
475 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
476 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
477 }
478
479 #[cfg(not(target_os = "fuchsia"))]
480 Stdio::Null => {
481 let mut opts = OpenOptions::new();
482 opts.read(readable);
483 opts.write(!readable);
484 let fd = File::open_c(DEV_NULL, &opts)?;
485 Ok((ChildStdio::Owned(fd.into_inner()), None))
486 }
487
488 #[cfg(target_os = "fuchsia")]
489 Stdio::Null => Ok((ChildStdio::Null, None)),
490 }
491 }
492}
493
494impl From<AnonPipe> for Stdio {
495 fn from(pipe: AnonPipe) -> Stdio {
496 Stdio::Fd(pipe.into_inner())
497 }
498}
499
500impl From<File> for Stdio {
501 fn from(file: File) -> Stdio {
502 Stdio::Fd(file.into_inner())
503 }
504}
505
506impl From<io::Stdout> for Stdio {
507 fn from(_: io::Stdout) -> Stdio {
508 // This ought really to be is Stdio::StaticFd(input_argument.as_fd()).
509 // But AsFd::as_fd takes its argument by reference, and yields
510 // a bounded lifetime, so it's no use here. There is no AsStaticFd.
511 //
512 // Additionally AsFd is only implemented for the *locked* versions.
513 // We don't want to lock them here. (The implications of not locking
514 // are the same as those for process::Stdio::inherit().)
515 //
516 // Arguably the hypothetical AsStaticFd and AsFd<'static>
517 // should be implemented for io::Stdout, not just for StdoutLocked.
518 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(fd:libc::STDOUT_FILENO) })
519 }
520}
521
522impl From<io::Stderr> for Stdio {
523 fn from(_: io::Stderr) -> Stdio {
524 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(fd:libc::STDERR_FILENO) })
525 }
526}
527
528impl ChildStdio {
529 pub fn fd(&self) -> Option<c_int> {
530 match *self {
531 ChildStdio::Inherit => None,
532 ChildStdio::Explicit(fd: i32) => Some(fd),
533 ChildStdio::Owned(ref fd: &FileDesc) => Some(fd.as_raw_fd()),
534
535 #[cfg(target_os = "fuchsia")]
536 ChildStdio::Null => None,
537 }
538 }
539}
540
541impl fmt::Debug for Command {
542 // show all attributes but `self.closures` which does not implement `Debug`
543 // and `self.argv` which is not useful for debugging
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 if f.alternate() {
546 let mut debug_command = f.debug_struct("Command");
547 debug_command.field("program", &self.program).field("args", &self.args);
548 if !self.env.is_unchanged() {
549 debug_command.field("env", &self.env);
550 }
551
552 if self.cwd.is_some() {
553 debug_command.field("cwd", &self.cwd);
554 }
555 if self.uid.is_some() {
556 debug_command.field("uid", &self.uid);
557 }
558 if self.gid.is_some() {
559 debug_command.field("gid", &self.gid);
560 }
561
562 if self.groups.is_some() {
563 debug_command.field("groups", &self.groups);
564 }
565
566 if self.stdin.is_some() {
567 debug_command.field("stdin", &self.stdin);
568 }
569 if self.stdout.is_some() {
570 debug_command.field("stdout", &self.stdout);
571 }
572 if self.stderr.is_some() {
573 debug_command.field("stderr", &self.stderr);
574 }
575 if self.pgroup.is_some() {
576 debug_command.field("pgroup", &self.pgroup);
577 }
578
579 #[cfg(target_os = "linux")]
580 {
581 debug_command.field("create_pidfd", &self.create_pidfd);
582 }
583
584 debug_command.finish()
585 } else {
586 if let Some(ref cwd) = self.cwd {
587 write!(f, "cd {cwd:?} && ")?;
588 }
589 if self.env.does_clear() {
590 write!(f, "env -i ")?;
591 // Altered env vars will be printed next, that should exactly work as expected.
592 } else {
593 // Removed env vars need the command to be wrapped in `env`.
594 let mut any_removed = false;
595 for (key, value_opt) in self.get_envs() {
596 if value_opt.is_none() {
597 if !any_removed {
598 write!(f, "env ")?;
599 any_removed = true;
600 }
601 write!(f, "-u {} ", key.to_string_lossy())?;
602 }
603 }
604 }
605 // Altered env vars can just be added in front of the program.
606 for (key, value_opt) in self.get_envs() {
607 if let Some(value) = value_opt {
608 write!(f, "{}={value:?} ", key.to_string_lossy())?;
609 }
610 }
611 if self.program != self.args[0] {
612 write!(f, "[{:?}] ", self.program)?;
613 }
614 write!(f, "{:?}", self.args[0])?;
615
616 for arg in &self.args[1..] {
617 write!(f, " {:?}", arg)?;
618 }
619 Ok(())
620 }
621 }
622}
623
624#[derive(PartialEq, Eq, Clone, Copy)]
625pub struct ExitCode(u8);
626
627impl fmt::Debug for ExitCode {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.debug_tuple(name:"unix_exit_status").field(&self.0).finish()
630 }
631}
632
633impl ExitCode {
634 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
635 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
636
637 #[inline]
638 pub fn as_i32(&self) -> i32 {
639 self.0 as i32
640 }
641}
642
643impl From<u8> for ExitCode {
644 fn from(code: u8) -> Self {
645 Self(code)
646 }
647}
648
649pub struct CommandArgs<'a> {
650 iter: crate::slice::Iter<'a, CString>,
651}
652
653impl<'a> Iterator for CommandArgs<'a> {
654 type Item = &'a OsStr;
655 fn next(&mut self) -> Option<&'a OsStr> {
656 self.iter.next().map(|cs: &CString| OsStr::from_bytes(slice:cs.as_bytes()))
657 }
658 fn size_hint(&self) -> (usize, Option<usize>) {
659 self.iter.size_hint()
660 }
661}
662
663impl<'a> ExactSizeIterator for CommandArgs<'a> {
664 fn len(&self) -> usize {
665 self.iter.len()
666 }
667 fn is_empty(&self) -> bool {
668 self.iter.is_empty()
669 }
670}
671
672impl<'a> fmt::Debug for CommandArgs<'a> {
673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674 f.debug_list().entries(self.iter.clone()).finish()
675 }
676}
677