1#[cfg(all(test, not(target_os = "emscripten")))]
2mod tests;
3
4use libc::{EXIT_FAILURE, EXIT_SUCCESS, c_char, c_int, gid_t, pid_t, uid_t};
5
6use crate::collections::BTreeMap;
7use crate::ffi::{CStr, CString, OsStr, OsString};
8use crate::os::unix::prelude::*;
9use crate::path::Path;
10use crate::sys::fd::FileDesc;
11use crate::sys::fs::File;
12#[cfg(not(target_os = "fuchsia"))]
13use crate::sys::fs::OpenOptions;
14use crate::sys::pipe::{self, AnonPipe};
15use crate::sys_common::process::{CommandEnv, CommandEnvs};
16use crate::sys_common::{FromInner, IntoInner};
17use crate::{fmt, io, ptr};
18
19cfg_if::cfg_if! {
20 if #[cfg(target_os = "fuchsia")] {
21 } else if #[cfg(target_os = "redox")] {
23 const DEV_NULL: &CStr = c"null:";
24 } else if #[cfg(target_os = "vxworks")] {
25 const DEV_NULL: &CStr = c"/null";
26 } else {
27 const DEV_NULL: &CStr = c"/dev/null";
28 }
29}
30
31cfg_if::cfg_if! {
37 if #[cfg(target_os = "android")] {
38 #[allow(dead_code)]
39 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
40 set.write_bytes(0u8, 1);
41 return 0;
42 }
43
44 #[allow(dead_code)]
45 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
46 use crate::slice;
47 use libc::{c_ulong, sigset_t};
48
49 const _: () = assert!(
53 align_of::<c_ulong>() == align_of::<sigset_t>()
54 && (size_of::<sigset_t>() % size_of::<c_ulong>()) == 0
55 );
56
57 let bit = (signum - 1) as usize;
58 if set.is_null() || bit >= (8 * size_of::<sigset_t>()) {
59 crate::sys::pal::unix::os::set_errno(libc::EINVAL);
60 return -1;
61 }
62 let raw = slice::from_raw_parts_mut(
63 set as *mut c_ulong,
64 size_of::<sigset_t>() / size_of::<c_ulong>(),
65 );
66 const LONG_BIT: usize = size_of::<c_ulong>() * 8;
67 raw[bit / LONG_BIT] |= 1 << (bit % LONG_BIT);
68 return 0;
69 }
70 } else {
71 #[allow(unused_imports)]
72 pub use libc::{sigemptyset, sigaddset};
73 }
74}
75
76pub struct Command {
81 program: CString,
82 args: Vec<CString>,
83 argv: Argv,
89 env: CommandEnv,
90
91 program_kind: ProgramKind,
92 cwd: Option<CString>,
93 uid: Option<uid_t>,
94 gid: Option<gid_t>,
95 saw_nul: bool,
96 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
97 groups: Option<Box<[gid_t]>>,
98 stdin: Option<Stdio>,
99 stdout: Option<Stdio>,
100 stderr: Option<Stdio>,
101 #[cfg(target_os = "linux")]
102 create_pidfd: bool,
103 pgroup: Option<pid_t>,
104}
105
106struct Argv(Vec<*const c_char>);
108
109unsafe impl Send for Argv {}
112unsafe impl Sync for Argv {}
113
114pub struct StdioPipes {
117 pub stdin: Option<AnonPipe>,
118 pub stdout: Option<AnonPipe>,
119 pub stderr: Option<AnonPipe>,
120}
121
122#[cfg_attr(target_os = "vita", allow(dead_code))]
125pub struct ChildPipes {
126 pub stdin: ChildStdio,
127 pub stdout: ChildStdio,
128 pub stderr: ChildStdio,
129}
130
131pub enum ChildStdio {
132 Inherit,
133 Explicit(c_int),
134 Owned(FileDesc),
135
136 #[cfg(target_os = "fuchsia")]
139 Null,
140}
141
142#[derive(Debug)]
143pub enum Stdio {
144 Inherit,
145 Null,
146 MakePipe,
147 Fd(FileDesc),
148 StaticFd(BorrowedFd<'static>),
149}
150
151#[derive(Copy, Clone, Debug, Eq, PartialEq)]
152pub enum ProgramKind {
153 PathLookup,
155 Relative,
157 Absolute,
159}
160
161impl ProgramKind {
162 fn new(program: &OsStr) -> Self {
163 if program.as_encoded_bytes().starts_with(b"/") {
164 Self::Absolute
165 } else if program.as_encoded_bytes().contains(&b'/') {
166 Self::Relative
168 } else {
169 Self::PathLookup
170 }
171 }
172}
173
174impl Command {
175 #[cfg(not(target_os = "linux"))]
176 pub fn new(program: &OsStr) -> Command {
177 let mut saw_nul = false;
178 let program_kind = ProgramKind::new(program.as_ref());
179 let program = os2c(program, &mut saw_nul);
180 Command {
181 argv: Argv(vec![program.as_ptr(), ptr::null()]),
182 args: vec![program.clone()],
183 program,
184 program_kind,
185 env: Default::default(),
186 cwd: None,
187 uid: None,
188 gid: None,
189 saw_nul,
190 closures: Vec::new(),
191 groups: None,
192 stdin: None,
193 stdout: None,
194 stderr: None,
195 pgroup: None,
196 }
197 }
198
199 #[cfg(target_os = "linux")]
200 pub fn new(program: &OsStr) -> Command {
201 let mut saw_nul = false;
202 let program_kind = ProgramKind::new(program.as_ref());
203 let program = os2c(program, &mut saw_nul);
204 Command {
205 argv: Argv(vec![program.as_ptr(), ptr::null()]),
206 args: vec![program.clone()],
207 program,
208 program_kind,
209 env: Default::default(),
210 cwd: None,
211 uid: None,
212 gid: None,
213 saw_nul,
214 closures: Vec::new(),
215 groups: None,
216 stdin: None,
217 stdout: None,
218 stderr: None,
219 create_pidfd: false,
220 pgroup: None,
221 }
222 }
223
224 pub fn set_arg_0(&mut self, arg: &OsStr) {
225 let arg = os2c(arg, &mut self.saw_nul);
227 debug_assert!(self.argv.0.len() > 1);
228 self.argv.0[0] = arg.as_ptr();
229 self.args[0] = arg;
230 }
231
232 pub fn arg(&mut self, arg: &OsStr) {
233 let arg = os2c(arg, &mut self.saw_nul);
236 self.argv.0[self.args.len()] = arg.as_ptr();
237 self.argv.0.push(ptr::null());
238
239 self.args.push(arg);
242 }
243
244 pub fn cwd(&mut self, dir: &OsStr) {
245 self.cwd = Some(os2c(dir, &mut self.saw_nul));
246 }
247 pub fn uid(&mut self, id: uid_t) {
248 self.uid = Some(id);
249 }
250 pub fn gid(&mut self, id: gid_t) {
251 self.gid = Some(id);
252 }
253 pub fn groups(&mut self, groups: &[gid_t]) {
254 self.groups = Some(Box::from(groups));
255 }
256 pub fn pgroup(&mut self, pgroup: pid_t) {
257 self.pgroup = Some(pgroup);
258 }
259
260 #[cfg(target_os = "linux")]
261 pub fn create_pidfd(&mut self, val: bool) {
262 self.create_pidfd = val;
263 }
264
265 #[cfg(not(target_os = "linux"))]
266 #[allow(dead_code)]
267 pub fn get_create_pidfd(&self) -> bool {
268 false
269 }
270
271 #[cfg(target_os = "linux")]
272 pub fn get_create_pidfd(&self) -> bool {
273 self.create_pidfd
274 }
275
276 pub fn saw_nul(&self) -> bool {
277 self.saw_nul
278 }
279
280 pub fn get_program(&self) -> &OsStr {
281 OsStr::from_bytes(self.program.as_bytes())
282 }
283
284 #[allow(dead_code)]
285 pub fn get_program_kind(&self) -> ProgramKind {
286 self.program_kind
287 }
288
289 pub fn get_args(&self) -> CommandArgs<'_> {
290 let mut iter = self.args.iter();
291 iter.next();
292 CommandArgs { iter }
293 }
294
295 pub fn get_envs(&self) -> CommandEnvs<'_> {
296 self.env.iter()
297 }
298
299 pub fn get_current_dir(&self) -> Option<&Path> {
300 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
301 }
302
303 pub fn get_argv(&self) -> &Vec<*const c_char> {
304 &self.argv.0
305 }
306
307 pub fn get_program_cstr(&self) -> &CStr {
308 &*self.program
309 }
310
311 #[allow(dead_code)]
312 pub fn get_cwd(&self) -> Option<&CStr> {
313 self.cwd.as_deref()
314 }
315 #[allow(dead_code)]
316 pub fn get_uid(&self) -> Option<uid_t> {
317 self.uid
318 }
319 #[allow(dead_code)]
320 pub fn get_gid(&self) -> Option<gid_t> {
321 self.gid
322 }
323 #[allow(dead_code)]
324 pub fn get_groups(&self) -> Option<&[gid_t]> {
325 self.groups.as_deref()
326 }
327 #[allow(dead_code)]
328 pub fn get_pgroup(&self) -> Option<pid_t> {
329 self.pgroup
330 }
331
332 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
333 &mut self.closures
334 }
335
336 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
337 self.closures.push(f);
338 }
339
340 pub fn stdin(&mut self, stdin: Stdio) {
341 self.stdin = Some(stdin);
342 }
343
344 pub fn stdout(&mut self, stdout: Stdio) {
345 self.stdout = Some(stdout);
346 }
347
348 pub fn stderr(&mut self, stderr: Stdio) {
349 self.stderr = Some(stderr);
350 }
351
352 pub fn env_mut(&mut self) -> &mut CommandEnv {
353 &mut self.env
354 }
355
356 pub fn capture_env(&mut self) -> Option<CStringArray> {
357 let maybe_env = self.env.capture_if_changed();
358 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
359 }
360
361 #[allow(dead_code)]
362 pub fn env_saw_path(&self) -> bool {
363 self.env.have_changed_path()
364 }
365
366 #[allow(dead_code)]
367 pub fn program_is_path(&self) -> bool {
368 self.program.to_bytes().contains(&b'/')
369 }
370
371 pub fn setup_io(
372 &self,
373 default: Stdio,
374 needs_stdin: bool,
375 ) -> io::Result<(StdioPipes, ChildPipes)> {
376 let null = Stdio::Null;
377 let default_stdin = if needs_stdin { &default } else { &null };
378 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
379 let stdout = self.stdout.as_ref().unwrap_or(&default);
380 let stderr = self.stderr.as_ref().unwrap_or(&default);
381 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
382 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
383 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
384 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
385 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
386 Ok((ours, theirs))
387 }
388}
389
390fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
391 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
392 *saw_nul = true;
393 c"<string-with-nul>".to_owned()
394 })
395}
396
397pub struct CStringArray {
399 items: Vec<CString>,
400 ptrs: Vec<*const c_char>,
401}
402
403impl CStringArray {
404 pub fn with_capacity(capacity: usize) -> Self {
405 let mut result = CStringArray {
406 items: Vec::with_capacity(capacity),
407 ptrs: Vec::with_capacity(capacity + 1),
408 };
409 result.ptrs.push(ptr::null());
410 result
411 }
412 pub fn push(&mut self, item: CString) {
413 let l = self.ptrs.len();
414 self.ptrs[l - 1] = item.as_ptr();
415 self.ptrs.push(ptr::null());
416 self.items.push(item);
417 }
418 pub fn as_ptr(&self) -> *const *const c_char {
419 self.ptrs.as_ptr()
420 }
421}
422
423fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
424 let mut result = CStringArray::with_capacity(env.len());
425 for (mut k, v) in env {
426 k.reserve_exact(v.len() + 2);
428 k.push("=");
429 k.push(&v);
430
431 if let Ok(item) = CString::new(k.into_vec()) {
433 result.push(item);
434 } else {
435 *saw_nul = true;
436 }
437 }
438
439 result
440}
441
442impl Stdio {
443 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
444 match *self {
445 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
446
447 Stdio::Fd(ref fd) => {
455 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
456 Ok((ChildStdio::Owned(fd.duplicate()?), None))
457 } else {
458 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
459 }
460 }
461
462 Stdio::StaticFd(fd) => {
463 let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
464 Ok((ChildStdio::Owned(fd), None))
465 }
466
467 Stdio::MakePipe => {
468 let (reader, writer) = pipe::anon_pipe()?;
469 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
470 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
471 }
472
473 #[cfg(not(target_os = "fuchsia"))]
474 Stdio::Null => {
475 let mut opts = OpenOptions::new();
476 opts.read(readable);
477 opts.write(!readable);
478 let fd = File::open_c(DEV_NULL, &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
488impl From<AnonPipe> for Stdio {
489 fn from(pipe: AnonPipe) -> Stdio {
490 Stdio::Fd(pipe.into_inner())
491 }
492}
493
494impl From<File> for Stdio {
495 fn from(file: File) -> Stdio {
496 Stdio::Fd(file.into_inner())
497 }
498}
499
500impl From<io::Stdout> for Stdio {
501 fn from(_: io::Stdout) -> Stdio {
502 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) })
513 }
514}
515
516impl From<io::Stderr> for Stdio {
517 fn from(_: io::Stderr) -> Stdio {
518 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) })
519 }
520}
521
522impl ChildStdio {
523 pub fn fd(&self) -> Option<c_int> {
524 match *self {
525 ChildStdio::Inherit => None,
526 ChildStdio::Explicit(fd) => Some(fd),
527 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
528
529 #[cfg(target_os = "fuchsia")]
530 ChildStdio::Null => None,
531 }
532 }
533}
534
535impl fmt::Debug for Command {
536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 if f.alternate() {
540 let mut debug_command = f.debug_struct("Command");
541 debug_command.field("program", &self.program).field("args", &self.args);
542 if !self.env.is_unchanged() {
543 debug_command.field("env", &self.env);
544 }
545
546 if self.cwd.is_some() {
547 debug_command.field("cwd", &self.cwd);
548 }
549 if self.uid.is_some() {
550 debug_command.field("uid", &self.uid);
551 }
552 if self.gid.is_some() {
553 debug_command.field("gid", &self.gid);
554 }
555
556 if self.groups.is_some() {
557 debug_command.field("groups", &self.groups);
558 }
559
560 if self.stdin.is_some() {
561 debug_command.field("stdin", &self.stdin);
562 }
563 if self.stdout.is_some() {
564 debug_command.field("stdout", &self.stdout);
565 }
566 if self.stderr.is_some() {
567 debug_command.field("stderr", &self.stderr);
568 }
569 if self.pgroup.is_some() {
570 debug_command.field("pgroup", &self.pgroup);
571 }
572
573 #[cfg(target_os = "linux")]
574 {
575 debug_command.field("create_pidfd", &self.create_pidfd);
576 }
577
578 debug_command.finish()
579 } else {
580 if let Some(ref cwd) = self.cwd {
581 write!(f, "cd {cwd:?} && ")?;
582 }
583 if self.env.does_clear() {
584 write!(f, "env -i ")?;
585 } else {
587 let mut any_removed = false;
589 for (key, value_opt) in self.get_envs() {
590 if value_opt.is_none() {
591 if !any_removed {
592 write!(f, "env ")?;
593 any_removed = true;
594 }
595 write!(f, "-u {} ", key.to_string_lossy())?;
596 }
597 }
598 }
599 for (key, value_opt) in self.get_envs() {
601 if let Some(value) = value_opt {
602 write!(f, "{}={value:?} ", key.to_string_lossy())?;
603 }
604 }
605 if self.program != self.args[0] {
606 write!(f, "[{:?}] ", self.program)?;
607 }
608 write!(f, "{:?}", self.args[0])?;
609
610 for arg in &self.args[1..] {
611 write!(f, " {:?}", arg)?;
612 }
613 Ok(())
614 }
615 }
616}
617
618#[derive(PartialEq, Eq, Clone, Copy)]
619pub struct ExitCode(u8);
620
621impl fmt::Debug for ExitCode {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 f.debug_tuple("unix_exit_status").field(&self.0).finish()
624 }
625}
626
627impl ExitCode {
628 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
629 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
630
631 #[inline]
632 pub fn as_i32(&self) -> i32 {
633 self.0 as i32
634 }
635}
636
637impl From<u8> for ExitCode {
638 fn from(code: u8) -> Self {
639 Self(code)
640 }
641}
642
643pub struct CommandArgs<'a> {
644 iter: crate::slice::Iter<'a, CString>,
645}
646
647impl<'a> Iterator for CommandArgs<'a> {
648 type Item = &'a OsStr;
649 fn next(&mut self) -> Option<&'a OsStr> {
650 self.iter.next().map(|cs| OsStr::from_bytes(cs.as_bytes()))
651 }
652 fn size_hint(&self) -> (usize, Option<usize>) {
653 self.iter.size_hint()
654 }
655}
656
657impl<'a> ExactSizeIterator for CommandArgs<'a> {
658 fn len(&self) -> usize {
659 self.iter.len()
660 }
661 fn is_empty(&self) -> bool {
662 self.iter.is_empty()
663 }
664}
665
666impl<'a> fmt::Debug for CommandArgs<'a> {
667 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668 f.debug_list().entries(self.iter.clone()).finish()
669 }
670}