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::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 = "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::io::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(#[automatically_derived]
impl ::core::fmt::Debug for Stdio {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Stdio::Inherit => ::core::fmt::Formatter::write_str(f, "Inherit"),
Stdio::Null => ::core::fmt::Formatter::write_str(f, "Null"),
Stdio::MakePipe =>
::core::fmt::Formatter::write_str(f, "MakePipe"),
Stdio::Fd(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Fd",
&__self_0),
Stdio::StaticFd(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"StaticFd", &__self_0),
}
}
}Debug)]
129pub enum Stdio {
130 Inherit,
131 Null,
132 MakePipe,
133 Fd(FileDesc),
134 StaticFd(BorrowedFd<'static>),
135}
136
137#[derive(#[automatically_derived]
impl ::core::marker::Copy for ProgramKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProgramKind {
#[inline]
fn clone(&self) -> ProgramKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ProgramKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ProgramKind::PathLookup => "PathLookup",
ProgramKind::Relative => "Relative",
ProgramKind::Absolute => "Absolute",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ProgramKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ProgramKind {
#[inline]
fn eq(&self, other: &ProgramKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}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_env_clear(&self) -> bool {
267 self.env.does_clear()
268 }
269
270 pub fn get_resolved_envs(&self) -> CommandResolvedEnvs {
271 CommandResolvedEnvs::new(self.env.capture())
272 }
273
274 pub fn get_current_dir(&self) -> Option<&Path> {
275 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
276 }
277
278 pub fn get_argv(&self) -> &CStringArray {
279 &self.args
280 }
281
282 pub fn get_program_cstr(&self) -> &CStr {
283 &self.program
284 }
285
286 #[allow(dead_code)]
287 pub fn get_cwd(&self) -> Option<&CStr> {
288 self.cwd.as_deref()
289 }
290 #[allow(dead_code)]
291 pub fn get_uid(&self) -> Option<uid_t> {
292 self.uid
293 }
294 #[allow(dead_code)]
295 pub fn get_gid(&self) -> Option<gid_t> {
296 self.gid
297 }
298 #[allow(dead_code)]
299 pub fn get_groups(&self) -> Option<&[gid_t]> {
300 self.groups.as_deref()
301 }
302 #[allow(dead_code)]
303 pub fn get_pgroup(&self) -> Option<pid_t> {
304 self.pgroup
305 }
306 #[allow(dead_code)]
307 pub fn get_chroot(&self) -> Option<&CStr> {
308 self.chroot.as_deref()
309 }
310 #[allow(dead_code)]
311 pub fn get_setsid(&self) -> bool {
312 self.setsid
313 }
314
315 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
316 &mut self.closures
317 }
318
319 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
320 self.closures.push(f);
321 }
322
323 pub fn stdin(&mut self, stdin: Stdio) {
324 self.stdin = Some(stdin);
325 }
326
327 pub fn stdout(&mut self, stdout: Stdio) {
328 self.stdout = Some(stdout);
329 }
330
331 pub fn stderr(&mut self, stderr: Stdio) {
332 self.stderr = Some(stderr);
333 }
334
335 pub fn env_mut(&mut self) -> &mut CommandEnv {
336 &mut self.env
337 }
338
339 pub fn capture_env(&mut self) -> Option<CStringArray> {
340 let maybe_env = self.env.capture_if_changed();
341 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
342 }
343
344 #[allow(dead_code)]
345 pub fn env_saw_path(&self) -> bool {
346 self.env.have_changed_path()
347 }
348
349 #[allow(dead_code)]
350 pub fn program_is_path(&self) -> bool {
351 self.program.to_bytes().contains(&b'/')
352 }
353
354 pub fn setup_io(
355 &self,
356 default: Stdio,
357 needs_stdin: bool,
358 ) -> io::Result<(StdioPipes, ChildPipes)> {
359 let null = Stdio::Null;
360 let default_stdin = if needs_stdin { &default } else { &null };
361 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
362 let stdout = self.stdout.as_ref().unwrap_or(&default);
363 let stderr = self.stderr.as_ref().unwrap_or(&default);
364 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
365 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
366 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
367 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
368 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
369 Ok((ours, theirs))
370 }
371}
372
373fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
374 CString::new(s.as_bytes()).unwrap_or_else(|_e| {
375 *saw_nul = true;
376 c"<string-with-nul>".to_owned()
377 })
378}
379
380fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
381 let mut result = CStringArray::with_capacity(env.len());
382 for (mut k, v) in env {
383 k.reserve_exact(v.len() + 2);
385 k.push("=");
386 k.push(&v);
387
388 if let Ok(item) = CString::new(k.into_vec()) {
390 result.push(item);
391 } else {
392 *saw_nul = true;
393 }
394 }
395
396 result
397}
398
399impl Stdio {
400 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<ChildPipe>)> {
401 match *self {
402 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
403
404 Stdio::Fd(ref fd) => {
412 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
413 Ok((ChildStdio::Owned(fd.duplicate()?), None))
414 } else {
415 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
416 }
417 }
418
419 Stdio::StaticFd(fd) => {
420 let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
421 Ok((ChildStdio::Owned(fd), None))
422 }
423
424 Stdio::MakePipe => {
425 let (reader, writer) = pipe()?;
426 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
427 Ok((ChildStdio::Owned(theirs), Some(ours)))
428 }
429
430 #[cfg(not(target_os = "fuchsia"))]
431 Stdio::Null => {
432 let mut opts = OpenOptions::new();
433 opts.read(readable);
434 opts.write(!readable);
435 let fd = File::open_c(DEV_NULL, &opts)?;
436 Ok((ChildStdio::Owned(fd.into_inner()), None))
437 }
438
439 #[cfg(target_os = "fuchsia")]
440 Stdio::Null => Ok((ChildStdio::Null, None)),
441 }
442 }
443}
444
445impl From<FileDesc> for Stdio {
446 fn from(fd: FileDesc) -> Stdio {
447 Stdio::Fd(fd)
448 }
449}
450
451impl From<File> for Stdio {
452 fn from(file: File) -> Stdio {
453 Stdio::Fd(file.into_inner())
454 }
455}
456
457impl From<io::Stdout> for Stdio {
458 fn from(_: io::Stdout) -> Stdio {
459 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) })
470 }
471}
472
473impl From<io::Stderr> for Stdio {
474 fn from(_: io::Stderr) -> Stdio {
475 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) })
476 }
477}
478
479impl ChildStdio {
480 pub fn fd(&self) -> Option<c_int> {
481 match *self {
482 ChildStdio::Inherit => None,
483 ChildStdio::Explicit(fd) => Some(fd),
484 ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
485
486 #[cfg(target_os = "fuchsia")]
487 ChildStdio::Null => None,
488 }
489 }
490}
491
492impl fmt::Debug for Command {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 if f.alternate() {
497 let mut debug_command = f.debug_struct("Command");
498 debug_command.field("program", &self.program).field("args", &self.args);
499 if !self.env.is_unchanged() {
500 debug_command.field("env", &self.env);
501 }
502
503 if self.cwd.is_some() {
504 debug_command.field("cwd", &self.cwd);
505 }
506 if self.uid.is_some() {
507 debug_command.field("uid", &self.uid);
508 }
509 if self.gid.is_some() {
510 debug_command.field("gid", &self.gid);
511 }
512
513 if self.groups.is_some() {
514 debug_command.field("groups", &self.groups);
515 }
516
517 if self.stdin.is_some() {
518 debug_command.field("stdin", &self.stdin);
519 }
520 if self.stdout.is_some() {
521 debug_command.field("stdout", &self.stdout);
522 }
523 if self.stderr.is_some() {
524 debug_command.field("stderr", &self.stderr);
525 }
526 if self.pgroup.is_some() {
527 debug_command.field("pgroup", &self.pgroup);
528 }
529
530 #[cfg(target_os = "linux")]
531 {
532 debug_command.field("create_pidfd", &self.create_pidfd);
533 }
534
535 debug_command.finish()
536 } else {
537 if let Some(ref cwd) = self.cwd {
538 f.write_fmt(format_args!("cd {0:?} && ", cwd))write!(f, "cd {cwd:?} && ")?;
539 }
540 if self.env.does_clear() {
541 f.write_fmt(format_args!("env -i "))write!(f, "env -i ")?;
542 } else {
544 let mut any_removed = false;
546 for (key, value_opt) in self.get_envs() {
547 if value_opt.is_none() {
548 if !any_removed {
549 f.write_fmt(format_args!("env "))write!(f, "env ")?;
550 any_removed = true;
551 }
552 f.write_fmt(format_args!("-u {0} ", key.to_string_lossy()))write!(f, "-u {} ", key.to_string_lossy())?;
553 }
554 }
555 }
556 for (key, value_opt) in self.get_envs() {
558 if let Some(value) = value_opt {
559 f.write_fmt(format_args!("{0}={1:?} ", key.to_string_lossy(), value))write!(f, "{}={value:?} ", key.to_string_lossy())?;
560 }
561 }
562
563 if *self.program != self.args[0] {
564 f.write_fmt(format_args!("[{0:?}] ", self.program))write!(f, "[{:?}] ", self.program)?;
565 }
566 f.write_fmt(format_args!("{0:?}", &self.args[0]))write!(f, "{:?}", &self.args[0])?;
567
568 for arg in self.get_args() {
569 f.write_fmt(format_args!(" {0:?}", arg))write!(f, " {:?}", arg)?;
570 }
571
572 Ok(())
573 }
574 }
575}
576
577#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ExitCode {
#[inline]
fn eq(&self, other: &ExitCode) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExitCode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}Eq, #[automatically_derived]
impl ::core::clone::Clone for ExitCode {
#[inline]
fn clone(&self) -> ExitCode {
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ExitCode { }Copy)]
578pub struct ExitCode(u8);
579
580impl fmt::Debug for ExitCode {
581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582 f.debug_tuple("unix_exit_status").field(&self.0).finish()
583 }
584}
585
586impl ExitCode {
587 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
588 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
589
590 #[inline]
591 pub fn as_i32(&self) -> i32 {
592 self.0 as i32
593 }
594}
595
596impl From<u8> for ExitCode {
597 fn from(code: u8) -> Self {
598 Self(code)
599 }
600}
601
602pub struct CommandArgs<'a> {
603 iter: CStringIter<'a>,
604}
605
606impl<'a> Iterator for CommandArgs<'a> {
607 type Item = &'a OsStr;
608
609 fn next(&mut self) -> Option<&'a OsStr> {
610 self.iter.next().map(|cs| OsStr::from_bytes(cs.to_bytes()))
611 }
612
613 fn size_hint(&self) -> (usize, Option<usize>) {
614 self.iter.size_hint()
615 }
616}
617
618impl<'a> ExactSizeIterator for CommandArgs<'a> {
619 fn len(&self) -> usize {
620 self.iter.len()
621 }
622
623 fn is_empty(&self) -> bool {
624 self.iter.is_empty()
625 }
626}
627
628impl<'a> fmt::Debug for CommandArgs<'a> {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.debug_list().entries(self.iter.clone()).finish()
631 }
632}
633
634pub type ChildPipe = crate::sys::pipe::Pipe;
635
636pub fn read_output(
637 out: ChildPipe,
638 stdout: &mut Vec<u8>,
639 err: ChildPipe,
640 stderr: &mut Vec<u8>,
641) -> io::Result<()> {
642 out.set_nonblocking(true)?;
645 err.set_nonblocking(true)?;
646
647 let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
648 fds[0].fd = out.as_raw_fd();
649 fds[0].events = libc::POLLIN;
650 fds[1].fd = err.as_raw_fd();
651 fds[1].events = libc::POLLIN;
652 loop {
653 cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
655
656 if fds[0].revents != 0 && read(&out, stdout)? {
657 err.set_nonblocking(false)?;
658 return err.read_to_end(stderr).map(drop);
659 }
660 if fds[1].revents != 0 && read(&err, stderr)? {
661 out.set_nonblocking(false)?;
662 return out.read_to_end(stdout).map(drop);
663 }
664 }
665
666 fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> {
672 match fd.read_to_end(dst) {
673 Ok(_) => Ok(true),
674 Err(e) => {
675 if e.raw_os_error() == Some(libc::EWOULDBLOCK)
676 || e.raw_os_error() == Some(libc::EAGAIN)
677 {
678 Ok(false)
679 } else {
680 Err(e)
681 }
682 }
683 }
684 }
685}
686
687pub fn getpid() -> u32 {
688 unsafe { libc::getpid() as u32 }
689}
690
691pub fn getppid() -> u32 {
692 unsafe { libc::getppid() as u32 }
693}