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