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_if::cfg_if! {
24 if #[cfg(target_os = "fuchsia")] {
25 // fuchsia doesn't have /dev/null
26 } else if #[cfg(target_os = "vxworks")] {
27 const DEV_NULL: &CStr = c"/null";
28 } else {
29 const DEV_NULL: &CStr = c"/dev/null";
30 }
31}
32
33// Android with api less than 21 define sig* functions inline, so it is not
34// available for dynamic link. Implementing sigemptyset and sigaddset allow us
35// to support older Android version (independent of libc version).
36// The following implementations are based on
37// https://github.com/aosp-mirror/platform_bionic/blob/ad8dcd6023294b646e5a8288c0ed431b0845da49/libc/include/android/legacy_signal_inlines.h
38cfg_if::cfg_if! {
39 if #[cfg(target_os = "android")] {
40 #[allow(dead_code)]
41 pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
42 set.write_bytes(0u8, 1);
43 return 0;
44 }
45
46 #[allow(dead_code)]
47 pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
48 use crate::slice;
49 use libc::{c_ulong, sigset_t};
50
51 // The implementations from bionic (android libc) type pun `sigset_t` as an
52 // array of `c_ulong`. This works, but lets add a smoke check to make sure
53 // that doesn't change.
54 const _: () = assert!(
55 align_of::<c_ulong>() == align_of::<sigset_t>()
56 && (size_of::<sigset_t>() % size_of::<c_ulong>()) == 0
57 );
58
59 let bit = (signum - 1) as usize;
60 if set.is_null() || bit >= (8 * size_of::<sigset_t>()) {
61 crate::sys::pal::os::set_errno(libc::EINVAL);
62 return -1;
63 }
64 let raw = slice::from_raw_parts_mut(
65 set as *mut c_ulong,
66 size_of::<sigset_t>() / size_of::<c_ulong>(),
67 );
68 const LONG_BIT: usize = size_of::<c_ulong>() * 8;
69 raw[bit / LONG_BIT] |= 1 << (bit % LONG_BIT);
70 return 0;
71 }
72 } else {
73 #[allow(unused_imports)]
74 pub use libc::{sigemptyset, sigaddset};
75 }
76}
77
78////////////////////////////////////////////////////////////////////////////////
79// Command
80////////////////////////////////////////////////////////////////////////////////
81
82pub struct Command {
83 program: CString,
84 args: CStringArray,
85 env: CommandEnv,
86
87 program_kind: ProgramKind,
88 cwd: Option<CString>,
89 chroot: Option<CString>,
90 uid: Option<uid_t>,
91 gid: Option<gid_t>,
92 saw_nul: bool,
93 closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
94 groups: Option<Box<[gid_t]>>,
95 stdin: Option<Stdio>,
96 stdout: Option<Stdio>,
97 stderr: Option<Stdio>,
98 #[cfg(target_os = "linux")]
99 create_pidfd: bool,
100 pgroup: Option<pid_t>,
101}
102
103// passed back to std::process with the pipes connected to the child, if any
104// were requested
105pub struct StdioPipes {
106 pub stdin: Option<AnonPipe>,
107 pub stdout: Option<AnonPipe>,
108 pub stderr: Option<AnonPipe>,
109}
110
111// passed to do_exec() with configuration of what the child stdio should look
112// like
113#[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 // On Fuchsia, null stdio is the default, so we simply don't specify
126 // any actions at the time of spawning.
127 #[cfg(target_os = "fuchsia")]
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 /// A program that would be looked up on the PATH (e.g. `ls`)
143 PathLookup,
144 /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
145 Relative,
146 /// An absolute path.
147 Absolute,
148}
149
150impl ProgramKind {
151 fn new(program: &OsStr) -> Self {
152 if program.as_encoded_bytes().starts_with(needle:b"/") {
153 Self::Absolute
154 } else if program.as_encoded_bytes().contains(&b'/') {
155 // If the program has more than one component in it, it is a relative path.
156 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 }
189 }
190
191 pub fn set_arg_0(&mut self, arg: &OsStr) {
192 // Set a new arg0
193 let arg = os2c(arg, &mut self.saw_nul);
194 self.args.write(0, arg);
195 }
196
197 pub fn arg(&mut self, arg: &OsStr) {
198 let arg = os2c(arg, &mut self.saw_nul);
199 self.args.push(arg);
200 }
201
202 pub fn cwd(&mut self, dir: &OsStr) {
203 self.cwd = Some(os2c(dir, &mut self.saw_nul));
204 }
205 pub fn uid(&mut self, id: uid_t) {
206 self.uid = Some(id);
207 }
208 pub fn gid(&mut self, id: gid_t) {
209 self.gid = Some(id);
210 }
211 pub fn groups(&mut self, groups: &[gid_t]) {
212 self.groups = Some(Box::from(groups));
213 }
214 pub fn pgroup(&mut self, pgroup: pid_t) {
215 self.pgroup = Some(pgroup);
216 }
217 pub fn chroot(&mut self, dir: &Path) {
218 self.chroot = Some(os2c(dir.as_os_str(), &mut self.saw_nul));
219 if self.cwd.is_none() {
220 self.cwd(&OsStr::new("/"));
221 }
222 }
223
224 #[cfg(target_os = "linux")]
225 pub fn create_pidfd(&mut self, val: bool) {
226 self.create_pidfd = val;
227 }
228
229 #[cfg(not(target_os = "linux"))]
230 #[allow(dead_code)]
231 pub fn get_create_pidfd(&self) -> bool {
232 false
233 }
234
235 #[cfg(target_os = "linux")]
236 pub fn get_create_pidfd(&self) -> bool {
237 self.create_pidfd
238 }
239
240 pub fn saw_nul(&self) -> bool {
241 self.saw_nul
242 }
243
244 pub fn get_program(&self) -> &OsStr {
245 OsStr::from_bytes(self.program.as_bytes())
246 }
247
248 #[allow(dead_code)]
249 pub fn get_program_kind(&self) -> ProgramKind {
250 self.program_kind
251 }
252
253 pub fn get_args(&self) -> CommandArgs<'_> {
254 let mut iter = self.args.iter();
255 // argv[0] contains the program name, but we are only interested in the
256 // arguments so skip it.
257 iter.next();
258 CommandArgs { iter }
259 }
260
261 pub fn get_envs(&self) -> CommandEnvs<'_> {
262 self.env.iter()
263 }
264
265 pub fn get_current_dir(&self) -> Option<&Path> {
266 self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
267 }
268
269 pub fn get_argv(&self) -> &CStringArray {
270 &self.args
271 }
272
273 pub fn get_program_cstr(&self) -> &CStr {
274 &self.program
275 }
276
277 #[allow(dead_code)]
278 pub fn get_cwd(&self) -> Option<&CStr> {
279 self.cwd.as_deref()
280 }
281 #[allow(dead_code)]
282 pub fn get_uid(&self) -> Option<uid_t> {
283 self.uid
284 }
285 #[allow(dead_code)]
286 pub fn get_gid(&self) -> Option<gid_t> {
287 self.gid
288 }
289 #[allow(dead_code)]
290 pub fn get_groups(&self) -> Option<&[gid_t]> {
291 self.groups.as_deref()
292 }
293 #[allow(dead_code)]
294 pub fn get_pgroup(&self) -> Option<pid_t> {
295 self.pgroup
296 }
297 #[allow(dead_code)]
298 pub fn get_chroot(&self) -> Option<&CStr> {
299 self.chroot.as_deref()
300 }
301
302 pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
303 &mut self.closures
304 }
305
306 pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
307 self.closures.push(f);
308 }
309
310 pub fn stdin(&mut self, stdin: Stdio) {
311 self.stdin = Some(stdin);
312 }
313
314 pub fn stdout(&mut self, stdout: Stdio) {
315 self.stdout = Some(stdout);
316 }
317
318 pub fn stderr(&mut self, stderr: Stdio) {
319 self.stderr = Some(stderr);
320 }
321
322 pub fn env_mut(&mut self) -> &mut CommandEnv {
323 &mut self.env
324 }
325
326 pub fn capture_env(&mut self) -> Option<CStringArray> {
327 let maybe_env = self.env.capture_if_changed();
328 maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
329 }
330
331 #[allow(dead_code)]
332 pub fn env_saw_path(&self) -> bool {
333 self.env.have_changed_path()
334 }
335
336 #[allow(dead_code)]
337 pub fn program_is_path(&self) -> bool {
338 self.program.to_bytes().contains(&b'/')
339 }
340
341 pub fn setup_io(
342 &self,
343 default: Stdio,
344 needs_stdin: bool,
345 ) -> io::Result<(StdioPipes, ChildPipes)> {
346 let null = Stdio::Null;
347 let default_stdin = if needs_stdin { &default } else { &null };
348 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
349 let stdout = self.stdout.as_ref().unwrap_or(&default);
350 let stderr = self.stderr.as_ref().unwrap_or(&default);
351 let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
352 let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
353 let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
354 let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
355 let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
356 Ok((ours, theirs))
357 }
358}
359
360fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
361 CString::new(s.as_bytes()).unwrap_or_else(|_e: NulError| {
362 *saw_nul = true;
363 c"<string-with-nul>".to_owned()
364 })
365}
366
367fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
368 let mut result: CStringArray = CStringArray::with_capacity(env.len());
369 for (mut k: OsString, v: OsString) in env {
370 // Reserve additional space for '=' and null terminator
371 k.reserve_exact(additional:v.len() + 2);
372 k.push("=");
373 k.push(&v);
374
375 // Add the new entry into the array
376 if let Ok(item: CString) = CString::new(k.into_vec()) {
377 result.push(item);
378 } else {
379 *saw_nul = true;
380 }
381 }
382
383 result
384}
385
386impl Stdio {
387 pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
388 match *self {
389 Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
390
391 // Make sure that the source descriptors are not an stdio
392 // descriptor, otherwise the order which we set the child's
393 // descriptors may blow away a descriptor which we are hoping to
394 // save. For example, suppose we want the child's stderr to be the
395 // parent's stdout, and the child's stdout to be the parent's
396 // stderr. No matter which we dup first, the second will get
397 // overwritten prematurely.
398 Stdio::Fd(ref fd) => {
399 if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
400 Ok((ChildStdio::Owned(fd.duplicate()?), None))
401 } else {
402 Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
403 }
404 }
405
406 Stdio::StaticFd(fd) => {
407 let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
408 Ok((ChildStdio::Owned(fd), None))
409 }
410
411 Stdio::MakePipe => {
412 let (reader, writer) = pipe::anon_pipe()?;
413 let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
414 Ok((ChildStdio::Owned(theirs.into_inner()), Some(ours)))
415 }
416
417 #[cfg(not(target_os = "fuchsia"))]
418 Stdio::Null => {
419 let mut opts = OpenOptions::new();
420 opts.read(readable);
421 opts.write(!readable);
422 let fd = File::open_c(DEV_NULL, &opts)?;
423 Ok((ChildStdio::Owned(fd.into_inner()), None))
424 }
425
426 #[cfg(target_os = "fuchsia")]
427 Stdio::Null => Ok((ChildStdio::Null, None)),
428 }
429 }
430}
431
432impl From<AnonPipe> for Stdio {
433 fn from(pipe: AnonPipe) -> Stdio {
434 Stdio::Fd(pipe.into_inner())
435 }
436}
437
438impl From<FileDesc> for Stdio {
439 fn from(fd: FileDesc) -> Stdio {
440 Stdio::Fd(fd)
441 }
442}
443
444impl From<File> for Stdio {
445 fn from(file: File) -> Stdio {
446 Stdio::Fd(file.into_inner())
447 }
448}
449
450impl From<io::Stdout> for Stdio {
451 fn from(_: io::Stdout) -> Stdio {
452 // This ought really to be is Stdio::StaticFd(input_argument.as_fd()).
453 // But AsFd::as_fd takes its argument by reference, and yields
454 // a bounded lifetime, so it's no use here. There is no AsStaticFd.
455 //
456 // Additionally AsFd is only implemented for the *locked* versions.
457 // We don't want to lock them here. (The implications of not locking
458 // are the same as those for process::Stdio::inherit().)
459 //
460 // Arguably the hypothetical AsStaticFd and AsFd<'static>
461 // should be implemented for io::Stdout, not just for StdoutLocked.
462 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(fd:libc::STDOUT_FILENO) })
463 }
464}
465
466impl From<io::Stderr> for Stdio {
467 fn from(_: io::Stderr) -> Stdio {
468 Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(fd:libc::STDERR_FILENO) })
469 }
470}
471
472impl ChildStdio {
473 pub fn fd(&self) -> Option<c_int> {
474 match *self {
475 ChildStdio::Inherit => None,
476 ChildStdio::Explicit(fd: i32) => Some(fd),
477 ChildStdio::Owned(ref fd: &FileDesc) => Some(fd.as_raw_fd()),
478
479 #[cfg(target_os = "fuchsia")]
480 ChildStdio::Null => None,
481 }
482 }
483}
484
485impl fmt::Debug for Command {
486 // show all attributes but `self.closures` which does not implement `Debug`
487 // and `self.argv` which is not useful for debugging
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 if f.alternate() {
490 let mut debug_command = f.debug_struct("Command");
491 debug_command.field("program", &self.program).field("args", &self.args);
492 if !self.env.is_unchanged() {
493 debug_command.field("env", &self.env);
494 }
495
496 if self.cwd.is_some() {
497 debug_command.field("cwd", &self.cwd);
498 }
499 if self.uid.is_some() {
500 debug_command.field("uid", &self.uid);
501 }
502 if self.gid.is_some() {
503 debug_command.field("gid", &self.gid);
504 }
505
506 if self.groups.is_some() {
507 debug_command.field("groups", &self.groups);
508 }
509
510 if self.stdin.is_some() {
511 debug_command.field("stdin", &self.stdin);
512 }
513 if self.stdout.is_some() {
514 debug_command.field("stdout", &self.stdout);
515 }
516 if self.stderr.is_some() {
517 debug_command.field("stderr", &self.stderr);
518 }
519 if self.pgroup.is_some() {
520 debug_command.field("pgroup", &self.pgroup);
521 }
522
523 #[cfg(target_os = "linux")]
524 {
525 debug_command.field("create_pidfd", &self.create_pidfd);
526 }
527
528 debug_command.finish()
529 } else {
530 if let Some(ref cwd) = self.cwd {
531 write!(f, "cd {cwd:?} && ")?;
532 }
533 if self.env.does_clear() {
534 write!(f, "env -i ")?;
535 // Altered env vars will be printed next, that should exactly work as expected.
536 } else {
537 // Removed env vars need the command to be wrapped in `env`.
538 let mut any_removed = false;
539 for (key, value_opt) in self.get_envs() {
540 if value_opt.is_none() {
541 if !any_removed {
542 write!(f, "env ")?;
543 any_removed = true;
544 }
545 write!(f, "-u {} ", key.to_string_lossy())?;
546 }
547 }
548 }
549 // Altered env vars can just be added in front of the program.
550 for (key, value_opt) in self.get_envs() {
551 if let Some(value) = value_opt {
552 write!(f, "{}={value:?} ", key.to_string_lossy())?;
553 }
554 }
555
556 if *self.program != self.args[0] {
557 write!(f, "[{:?}] ", self.program)?;
558 }
559 write!(f, "{:?}", &self.args[0])?;
560
561 for arg in self.get_args() {
562 write!(f, " {:?}", arg)?;
563 }
564
565 Ok(())
566 }
567 }
568}
569
570#[derive(PartialEq, Eq, Clone, Copy)]
571pub struct ExitCode(u8);
572
573impl fmt::Debug for ExitCode {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 f.debug_tuple(name:"unix_exit_status").field(&self.0).finish()
576 }
577}
578
579impl ExitCode {
580 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
581 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
582
583 #[inline]
584 pub fn as_i32(&self) -> i32 {
585 self.0 as i32
586 }
587}
588
589impl From<u8> for ExitCode {
590 fn from(code: u8) -> Self {
591 Self(code)
592 }
593}
594
595pub struct CommandArgs<'a> {
596 iter: CStringIter<'a>,
597}
598
599impl<'a> Iterator for CommandArgs<'a> {
600 type Item = &'a OsStr;
601
602 fn next(&mut self) -> Option<&'a OsStr> {
603 self.iter.next().map(|cs: &'a CStr| OsStr::from_bytes(slice:cs.to_bytes()))
604 }
605
606 fn size_hint(&self) -> (usize, Option<usize>) {
607 self.iter.size_hint()
608 }
609}
610
611impl<'a> ExactSizeIterator for CommandArgs<'a> {
612 fn len(&self) -> usize {
613 self.iter.len()
614 }
615
616 fn is_empty(&self) -> bool {
617 self.iter.is_empty()
618 }
619}
620
621impl<'a> fmt::Debug for CommandArgs<'a> {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 f.debug_list().entries(self.iter.clone()).finish()
624 }
625}
626