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