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