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