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::{
47 mem::{align_of, size_of},
48 slice,
49 };
50 use libc::{c_ulong, sigset_t};
51
52 const _: () = assert!(
56 align_of::<c_ulong>() == align_of::<sigset_t>()
57 && (size_of::<sigset_t>() % size_of::<c_ulong>()) == 0
58 );
59
60 let bit = (signum - 1) as usize;
61 if set.is_null() || bit >= (8 * size_of::<sigset_t>()) {
62 crate::sys::pal::unix::os::set_errno(libc::EINVAL);
63 return -1;
64 }
65 let raw = slice::from_raw_parts_mut(
66 set as *mut c_ulong,
67 size_of::<sigset_t>() / size_of::<c_ulong>(),
68 );
69 const LONG_BIT: usize = size_of::<c_ulong>() * 8;
70 raw[bit / LONG_BIT] |= 1 << (bit % LONG_BIT);
71 return 0;
72 }
73 } else {
74 #[allow(unused_imports)]
75 pub use libc::{sigemptyset, sigaddset};
76 }
77}
78
79pub struct Command {
84 program: CString,
85 args: Vec<CString>,
86 argv: Argv,
92 env: CommandEnv,
93
94 program_kind: ProgramKind,
95 cwd: Option<CString>,
96 uid: Option<uid_t>,
97 gid: Option<gid_t>,
98 saw_nul: bool,
99 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
100 groups: Option<Box<[gid_t]>>,
101 stdin: Option<Stdio>,
102 stdout: Option<Stdio>,
103 stderr: Option<Stdio>,
104 #[cfg(target_os = "linux")]
105 create_pidfd: bool,
106 pgroup: Option<pid_t>,
107}
108
109struct Argv(Vec<*const c_char>);
111
112unsafe impl Send for Argv {}
115unsafe impl Sync for Argv {}
116
117pub struct StdioPipes {
120 pub stdin: Option<AnonPipe>,
121 pub stdout: Option<AnonPipe>,
122 pub stderr: Option<AnonPipe>,
123}
124
125#[cfg_attr(target_os = "vita", allow(dead_code))]
128pub struct ChildPipes {
129 pub stdin: ChildStdio,
130 pub stdout: ChildStdio,
131 pub stderr: ChildStdio,
132}
133
134pub enum ChildStdio {
135 Inherit,
136 Explicit(c_int),
137 Owned(FileDesc),
138
139 #[cfg(target_os = "fuchsia")]
142 Null,
143}
144
145#[derive(Debug)]
146pub enum Stdio {
147 Inherit,
148 Null,
149 MakePipe,
150 Fd(FileDesc),
151 StaticFd(BorrowedFd<'static>),
152}
153
154#[derive(Copy, Clone, Debug, Eq, PartialEq)]
155pub enum ProgramKind {
156 PathLookup,
158 Relative,
160 Absolute,
162}
163
164impl ProgramKind {
165 fn new(program: &OsStr) -> Self {
166 if program.as_encoded_bytes().starts_with(b"/") {
167 Self::Absolute
168 } else if program.as_encoded_bytes().contains(&b'/') {
169 Self::Relative
171 } else {
172 Self::PathLookup
173 }
174 }
175}
176
177impl Command {
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);
183 Command {
184 argv: Argv(vec![program.as_ptr(), ptr::null()]),
185 args: vec![program.clone()],
186 program,
187 program_kind,
188 env: Default::default(),
189 cwd: None,
190 uid: None,
191 gid: None,
192 saw_nul,
193 closures: Vec::new(),
194 groups: None,
195 stdin: None,
196 stdout: None,
197 stderr: None,
198 pgroup: None,
199 }
200 }
201
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);
207 Command {
208 argv: Argv(vec![program.as_ptr(), ptr::null()]),
209 args: vec![program.clone()],
210 program,
211 program_kind,
212 env: Default::default(),
213 cwd: None,
214 uid: None,
215 gid: None,
216 saw_nul,
217 closures: Vec::new(),
218 groups: None,
219 stdin: None,
220 stdout: None,
221 stderr: None,
222 create_pidfd: false,
223 pgroup: None,
224 }
225 }
226
227 pub fn set_arg_0(&mut self, arg: &OsStr) {
228 let arg = os2c(arg, &mut self.saw_nul);
230 debug_assert!(self.argv.0.len() > 1);
231 self.argv.0[0] = arg.as_ptr();
232 self.args[0] = arg;
233 }
234
235 pub fn arg(&mut self, arg: &OsStr) {
236 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());
241
242 self.args.push(arg);
245 }
246
247 pub fn cwd(&mut self, dir: &OsStr) {
248 self.cwd = Some(os2c(dir, &mut self.saw_nul));
249 }
250 pub fn uid(&mut self, id: uid_t) {
251 self.uid = Some(id);
252 }
253 pub fn gid(&mut self, id: gid_t) {
254 self.gid = Some(id);
255 }
256 pub fn groups(&mut self, groups: &[gid_t]) {
257 self.groups = Some(Box::from(groups));
258 }
259 pub fn pgroup(&mut self, pgroup: pid_t) {
260 self.pgroup = Some(pgroup);
261 }
262
263 #[cfg(target_os = "linux")]
264 pub fn create_pidfd(&mut self, val: bool) {
265 self.create_pidfd = val;
266 }
267
268 #[cfg(not(target_os = "linux"))]
269 #[allow(dead_code)]
270 pub fn get_create_pidfd(&self) -> bool {
271 false
272 }
273
274 #[cfg(target_os = "linux")]
275 pub fn get_create_pidfd(&self) -> bool {
276 self.create_pidfd
277 }
278
279 pub fn saw_nul(&self) -> bool {
280 self.saw_nul
281 }
282
283 pub fn get_program(&self) -> &OsStr {
284 OsStr::from_bytes(self.program.as_bytes())
285 }
286
287 #[allow(dead_code)]
288 pub fn get_program_kind(&self) -> ProgramKind {
289 self.program_kind
290 }
291
292 pub fn get_args(&self) -> CommandArgs<'_> {
293 let mut iter = self.args.iter();
294 iter.next();
295 CommandArgs { iter }
296 }
297
298 pub fn get_envs(&self) -> CommandEnvs<'_> {
299 self.env.iter()
300 }
301
302 pub fn get_current_dir(&self) -> Option<&Path> {
303 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
304 }
305
306 pub fn get_argv(&self) -> &Vec<*const c_char> {
307 &self.argv.0
308 }
309
310 pub fn get_program_cstr(&self) -> &CStr {
311 &*self.program
312 }
313
314 #[allow(dead_code)]
315 pub fn get_cwd(&self) -> Option<&CStr> {
316 self.cwd.as_deref()
317 }
318 #[allow(dead_code)]
319 pub fn get_uid(&self) -> Option<uid_t> {
320 self.uid
321 }
322 #[allow(dead_code)]
323 pub fn get_gid(&self) -> Option<gid_t> {
324 self.gid
325 }
326 #[allow(dead_code)]
327 pub fn get_groups(&self) -> Option<&[gid_t]> {
328 self.groups.as_deref()
329 }
330 #[allow(dead_code)]
331 pub fn get_pgroup(&self) -> Option<pid_t> {
332 self.pgroup
333 }
334
335 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
336 &mut self.closures
337 }
338
339 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
340 self.closures.push(f);
341 }
342
343 pub fn stdin(&mut self, stdin: Stdio) {
344 self.stdin = Some(stdin);
345 }
346
347 pub fn stdout(&mut self, stdout: Stdio) {
348 self.stdout = Some(stdout);
349 }
350
351 pub fn stderr(&mut self, stderr: Stdio) {
352 self.stderr = Some(stderr);
353 }
354
355 pub fn env_mut(&mut self) -> &mut CommandEnv {
356 &mut self.env
357 }
358
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))
362 }
363
364 #[allow(dead_code)]
365 pub fn env_saw_path(&self) -> bool {
366 self.env.have_changed_path()
367 }
368
369 #[allow(dead_code)]
370 pub fn program_is_path(&self) -> bool {
371 self.program.to_bytes().contains(&b'/')
372 }
373
374 pub fn setup_io(
375 &self,
376 default: Stdio,
377 needs_stdin: bool,
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 };
389 Ok((ours, theirs))
390 }
391}
392
393fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
394 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
395 *saw_nul = true;
396 c"<string-with-nul>".to_owned()
397 })
398}
399
400pub struct CStringArray {
402 items: Vec<CString>,
403 ptrs: Vec<*const c_char>,
404}
405
406impl CStringArray {
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),
411 };
412 result.ptrs.push(ptr::null());
413 result
414 }
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);
420 }
421 pub fn as_ptr(&self) -> *const *const c_char {
422 self.ptrs.as_ptr()
423 }
424}
425
426fn 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 k.reserve_exact(v.len() + 2);
431 k.push("=");
432 k.push(&v);
433
434 if let Ok(item) = CString::new(k.into_vec()) {
436 result.push(item);
437 } else {
438 *saw_nul = true;
439 }
440 }
441
442 result
443}
444
445impl Stdio {
446 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
447 match *self {
448 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
449
450 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))
460 } else {
461 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
462 }
463 }
464
465 Stdio::StaticFd(fd) => {
466 let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
467 Ok((ChildStdio::Owned(fd), None))
468 }
469
470 Stdio::MakePipe => {
471 let (reader, writer) = pipe::anon_pipe()?;
472 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
473 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
474 }
475
476 #[cfg(not(target_os = "fuchsia"))]
477 Stdio::Null => {
478 let mut opts = OpenOptions::new();
479 opts.read(readable);
480 opts.write(!readable);
481 let fd = File::open_c(DEV_NULL, &opts)?;
482 Ok((ChildStdio::Owned(fd.into_inner()), None))
483 }
484
485 #[cfg(target_os = "fuchsia")]
486 Stdio::Null => Ok((ChildStdio::Null, None)),
487 }
488 }
489}
490
491impl From<AnonPipe> for Stdio {
492 fn from(pipe: AnonPipe) -> Stdio {
493 Stdio::Fd(pipe.into_inner())
494 }
495}
496
497impl From<File> for Stdio {
498 fn from(file: File) -> Stdio {
499 Stdio::Fd(file.into_inner())
500 }
501}
502
503impl From<io::Stdout> for Stdio {
504 fn from(_: io::Stdout) -> Stdio {
505 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) })
516 }
517}
518
519impl From<io::Stderr> for Stdio {
520 fn from(_: io::Stderr) -> Stdio {
521 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) })
522 }
523}
524
525impl ChildStdio {
526 pub fn fd(&self) -> Option<c_int> {
527 match *self {
528 ChildStdio::Inherit => None,
529 ChildStdio::Explicit(fd) => Some(fd),
530 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
531
532 #[cfg(target_os = "fuchsia")]
533 ChildStdio::Null => None,
534 }
535 }
536}
537
538impl fmt::Debug for Command {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542 if f.alternate() {
543 let mut debug_command = f.debug_struct("Command");
544 debug_command.field("program", &self.program).field("args", &self.args);
545 if !self.env.is_unchanged() {
546 debug_command.field("env", &self.env);
547 }
548
549 if self.cwd.is_some() {
550 debug_command.field("cwd", &self.cwd);
551 }
552 if self.uid.is_some() {
553 debug_command.field("uid", &self.uid);
554 }
555 if self.gid.is_some() {
556 debug_command.field("gid", &self.gid);
557 }
558
559 if self.groups.is_some() {
560 debug_command.field("groups", &self.groups);
561 }
562
563 if self.stdin.is_some() {
564 debug_command.field("stdin", &self.stdin);
565 }
566 if self.stdout.is_some() {
567 debug_command.field("stdout", &self.stdout);
568 }
569 if self.stderr.is_some() {
570 debug_command.field("stderr", &self.stderr);
571 }
572 if self.pgroup.is_some() {
573 debug_command.field("pgroup", &self.pgroup);
574 }
575
576 #[cfg(target_os = "linux")]
577 {
578 debug_command.field("create_pidfd", &self.create_pidfd);
579 }
580
581 debug_command.finish()
582 } else {
583 if let Some(ref cwd) = self.cwd {
584 write!(f, "cd {cwd:?} && ")?;
585 }
586 if self.env.does_clear() {
587 write!(f, "env -i ")?;
588 } else {
590 let mut any_removed = false;
592 for (key, value_opt) in self.get_envs() {
593 if value_opt.is_none() {
594 if !any_removed {
595 write!(f, "env ")?;
596 any_removed = true;
597 }
598 write!(f, "-u {} ", key.to_string_lossy())?;
599 }
600 }
601 }
602 for (key, value_opt) in self.get_envs() {
604 if let Some(value) = value_opt {
605 write!(f, "{}={value:?} ", key.to_string_lossy())?;
606 }
607 }
608 if self.program != self.args[0] {
609 write!(f, "[{:?}] ", self.program)?;
610 }
611 write!(f, "{:?}", self.args[0])?;
612
613 for arg in &self.args[1..] {
614 write!(f, " {:?}", arg)?;
615 }
616 Ok(())
617 }
618 }
619}
620
621#[derive(PartialEq, Eq, Clone, Copy)]
622pub struct ExitCode(u8);
623
624impl fmt::Debug for ExitCode {
625 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626 f.debug_tuple("unix_exit_status").field(&self.0).finish()
627 }
628}
629
630impl ExitCode {
631 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
632 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
633
634 #[inline]
635 pub fn as_i32(&self) -> i32 {
636 self.0 as i32
637 }
638}
639
640impl From<u8> for ExitCode {
641 fn from(code: u8) -> Self {
642 Self(code)
643 }
644}
645
646pub struct CommandArgs<'a> {
647 iter: crate::slice::Iter<'a, CString>,
648}
649
650impl<'a> Iterator for CommandArgs<'a> {
651 type Item = &'a OsStr;
652 fn next(&mut self) -> Option<&'a OsStr> {
653 self.iter.next().map(|cs| OsStr::from_bytes(cs.as_bytes()))
654 }
655 fn size_hint(&self) -> (usize, Option<usize>) {
656 self.iter.size_hint()
657 }
658}
659
660impl<'a> ExactSizeIterator for CommandArgs<'a> {
661 fn len(&self) -> usize {
662 self.iter.len()
663 }
664 fn is_empty(&self) -> bool {
665 self.iter.is_empty()
666 }
667}
668
669impl<'a> fmt::Debug for CommandArgs<'a> {
670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671 f.debug_list().entries(self.iter.clone()).finish()
672 }
673}