std/sys/process/unix/
common.rs

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};
19use crate::sys::{FromInner, IntoInner, cvt_r};
20use crate::{fmt, io, mem};
21
22mod cstring_array;
23
24cfg_select! {
25    target_os = "fuchsia" => {
26        // fuchsia doesn't have /dev/null
27    }
28    target_os = "vxworks" => {
29        const DEV_NULL: &CStr = c"/null";
30    }
31    _ => {
32        const DEV_NULL: &CStr = c"/dev/null";
33    }
34}
35
36// Android with api less than 21 define sig* functions inline, so it is not
37// available for dynamic link. Implementing sigemptyset and sigaddset allow us
38// to support older Android version (independent of libc version).
39// The following implementations are based on
40// https://github.com/aosp-mirror/platform_bionic/blob/ad8dcd6023294b646e5a8288c0ed431b0845da49/libc/include/android/legacy_signal_inlines.h
41cfg_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            // The implementations from bionic (android libc) type pun `sigset_t` as an
55            // array of `c_ulong`. This works, but lets add a smoke check to make sure
56            // that doesn't change.
57            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
82////////////////////////////////////////////////////////////////////////////////
83// Command
84////////////////////////////////////////////////////////////////////////////////
85
86pub 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// passed to do_exec() with configuration of what the child stdio should look
109// like
110#[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    // On Fuchsia, null stdio is the default, so we simply don't specify
123    // any actions at the time of spawning.
124    #[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    /// A program that would be looked up on the PATH (e.g. `ls`)
140    PathLookup,
141    /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
142    Relative,
143    /// An absolute path.
144    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            // If the program has more than one component in it, it is a relative path.
153            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        // Set a new arg0
191        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        // argv[0] contains the program name, but we are only interested in the
257        // arguments so skip it.
258        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_current_dir(&self) -> Option<&Path> {
271        self.cwd.as_ref().map(|cs| Path::new(OsStr::from_bytes(cs.as_bytes())))
272    }
273
274    pub fn get_argv(&self) -> &CStringArray {
275        &self.args
276    }
277
278    pub fn get_program_cstr(&self) -> &CStr {
279        &self.program
280    }
281
282    #[allow(dead_code)]
283    pub fn get_cwd(&self) -> Option<&CStr> {
284        self.cwd.as_deref()
285    }
286    #[allow(dead_code)]
287    pub fn get_uid(&self) -> Option<uid_t> {
288        self.uid
289    }
290    #[allow(dead_code)]
291    pub fn get_gid(&self) -> Option<gid_t> {
292        self.gid
293    }
294    #[allow(dead_code)]
295    pub fn get_groups(&self) -> Option<&[gid_t]> {
296        self.groups.as_deref()
297    }
298    #[allow(dead_code)]
299    pub fn get_pgroup(&self) -> Option<pid_t> {
300        self.pgroup
301    }
302    #[allow(dead_code)]
303    pub fn get_chroot(&self) -> Option<&CStr> {
304        self.chroot.as_deref()
305    }
306    #[allow(dead_code)]
307    pub fn get_setsid(&self) -> bool {
308        self.setsid
309    }
310
311    pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
312        &mut self.closures
313    }
314
315    pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
316        self.closures.push(f);
317    }
318
319    pub fn stdin(&mut self, stdin: Stdio) {
320        self.stdin = Some(stdin);
321    }
322
323    pub fn stdout(&mut self, stdout: Stdio) {
324        self.stdout = Some(stdout);
325    }
326
327    pub fn stderr(&mut self, stderr: Stdio) {
328        self.stderr = Some(stderr);
329    }
330
331    pub fn env_mut(&mut self) -> &mut CommandEnv {
332        &mut self.env
333    }
334
335    pub fn capture_env(&mut self) -> Option<CStringArray> {
336        let maybe_env = self.env.capture_if_changed();
337        maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
338    }
339
340    #[allow(dead_code)]
341    pub fn env_saw_path(&self) -> bool {
342        self.env.have_changed_path()
343    }
344
345    #[allow(dead_code)]
346    pub fn program_is_path(&self) -> bool {
347        self.program.to_bytes().contains(&b'/')
348    }
349
350    pub fn setup_io(
351        &self,
352        default: Stdio,
353        needs_stdin: bool,
354    ) -> io::Result<(StdioPipes, ChildPipes)> {
355        let null = Stdio::Null;
356        let default_stdin = if needs_stdin { &default } else { &null };
357        let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
358        let stdout = self.stdout.as_ref().unwrap_or(&default);
359        let stderr = self.stderr.as_ref().unwrap_or(&default);
360        let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
361        let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
362        let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
363        let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
364        let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
365        Ok((ours, theirs))
366    }
367}
368
369fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
370    CString::new(s.as_bytes()).unwrap_or_else(|_e| {
371        *saw_nul = true;
372        c"<string-with-nul>".to_owned()
373    })
374}
375
376fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
377    let mut result = CStringArray::with_capacity(env.len());
378    for (mut k, v) in env {
379        // Reserve additional space for '=' and null terminator
380        k.reserve_exact(v.len() + 2);
381        k.push("=");
382        k.push(&v);
383
384        // Add the new entry into the array
385        if let Ok(item) = CString::new(k.into_vec()) {
386            result.push(item);
387        } else {
388            *saw_nul = true;
389        }
390    }
391
392    result
393}
394
395impl Stdio {
396    pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<ChildPipe>)> {
397        match *self {
398            Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
399
400            // Make sure that the source descriptors are not an stdio
401            // descriptor, otherwise the order which we set the child's
402            // descriptors may blow away a descriptor which we are hoping to
403            // save. For example, suppose we want the child's stderr to be the
404            // parent's stdout, and the child's stdout to be the parent's
405            // stderr. No matter which we dup first, the second will get
406            // overwritten prematurely.
407            Stdio::Fd(ref fd) => {
408                if fd.as_raw_fd() >= 0 && fd.as_raw_fd() <= libc::STDERR_FILENO {
409                    Ok((ChildStdio::Owned(fd.duplicate()?), None))
410                } else {
411                    Ok((ChildStdio::Explicit(fd.as_raw_fd()), None))
412                }
413            }
414
415            Stdio::StaticFd(fd) => {
416                let fd = FileDesc::from_inner(fd.try_clone_to_owned()?);
417                Ok((ChildStdio::Owned(fd), None))
418            }
419
420            Stdio::MakePipe => {
421                let (reader, writer) = pipe()?;
422                let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
423                Ok((ChildStdio::Owned(theirs), Some(ours)))
424            }
425
426            #[cfg(not(target_os = "fuchsia"))]
427            Stdio::Null => {
428                let mut opts = OpenOptions::new();
429                opts.read(readable);
430                opts.write(!readable);
431                let fd = File::open_c(DEV_NULL, &opts)?;
432                Ok((ChildStdio::Owned(fd.into_inner()), None))
433            }
434
435            #[cfg(target_os = "fuchsia")]
436            Stdio::Null => Ok((ChildStdio::Null, None)),
437        }
438    }
439}
440
441impl From<FileDesc> for Stdio {
442    fn from(fd: FileDesc) -> Stdio {
443        Stdio::Fd(fd)
444    }
445}
446
447impl From<File> for Stdio {
448    fn from(file: File) -> Stdio {
449        Stdio::Fd(file.into_inner())
450    }
451}
452
453impl From<io::Stdout> for Stdio {
454    fn from(_: io::Stdout) -> Stdio {
455        // This ought really to be is Stdio::StaticFd(input_argument.as_fd()).
456        // But AsFd::as_fd takes its argument by reference, and yields
457        // a bounded lifetime, so it's no use here. There is no AsStaticFd.
458        //
459        // Additionally AsFd is only implemented for the *locked* versions.
460        // We don't want to lock them here.  (The implications of not locking
461        // are the same as those for process::Stdio::inherit().)
462        //
463        // Arguably the hypothetical AsStaticFd and AsFd<'static>
464        // should be implemented for io::Stdout, not just for StdoutLocked.
465        Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) })
466    }
467}
468
469impl From<io::Stderr> for Stdio {
470    fn from(_: io::Stderr) -> Stdio {
471        Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) })
472    }
473}
474
475impl ChildStdio {
476    pub fn fd(&self) -> Option<c_int> {
477        match *self {
478            ChildStdio::Inherit => None,
479            ChildStdio::Explicit(fd) => Some(fd),
480            ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
481
482            #[cfg(target_os = "fuchsia")]
483            ChildStdio::Null => None,
484        }
485    }
486}
487
488impl fmt::Debug for Command {
489    // show all attributes but `self.closures` which does not implement `Debug`
490    // and `self.argv` which is not useful for debugging
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        if f.alternate() {
493            let mut debug_command = f.debug_struct("Command");
494            debug_command.field("program", &self.program).field("args", &self.args);
495            if !self.env.is_unchanged() {
496                debug_command.field("env", &self.env);
497            }
498
499            if self.cwd.is_some() {
500                debug_command.field("cwd", &self.cwd);
501            }
502            if self.uid.is_some() {
503                debug_command.field("uid", &self.uid);
504            }
505            if self.gid.is_some() {
506                debug_command.field("gid", &self.gid);
507            }
508
509            if self.groups.is_some() {
510                debug_command.field("groups", &self.groups);
511            }
512
513            if self.stdin.is_some() {
514                debug_command.field("stdin", &self.stdin);
515            }
516            if self.stdout.is_some() {
517                debug_command.field("stdout", &self.stdout);
518            }
519            if self.stderr.is_some() {
520                debug_command.field("stderr", &self.stderr);
521            }
522            if self.pgroup.is_some() {
523                debug_command.field("pgroup", &self.pgroup);
524            }
525
526            #[cfg(target_os = "linux")]
527            {
528                debug_command.field("create_pidfd", &self.create_pidfd);
529            }
530
531            debug_command.finish()
532        } else {
533            if let Some(ref cwd) = self.cwd {
534                write!(f, "cd {cwd:?} && ")?;
535            }
536            if self.env.does_clear() {
537                write!(f, "env -i ")?;
538                // Altered env vars will be printed next, that should exactly work as expected.
539            } else {
540                // Removed env vars need the command to be wrapped in `env`.
541                let mut any_removed = false;
542                for (key, value_opt) in self.get_envs() {
543                    if value_opt.is_none() {
544                        if !any_removed {
545                            write!(f, "env ")?;
546                            any_removed = true;
547                        }
548                        write!(f, "-u {} ", key.to_string_lossy())?;
549                    }
550                }
551            }
552            // Altered env vars can just be added in front of the program.
553            for (key, value_opt) in self.get_envs() {
554                if let Some(value) = value_opt {
555                    write!(f, "{}={value:?} ", key.to_string_lossy())?;
556                }
557            }
558
559            if *self.program != self.args[0] {
560                write!(f, "[{:?}] ", self.program)?;
561            }
562            write!(f, "{:?}", &self.args[0])?;
563
564            for arg in self.get_args() {
565                write!(f, " {:?}", arg)?;
566            }
567
568            Ok(())
569        }
570    }
571}
572
573#[derive(PartialEq, Eq, Clone, Copy)]
574pub struct ExitCode(u8);
575
576impl fmt::Debug for ExitCode {
577    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
578        f.debug_tuple("unix_exit_status").field(&self.0).finish()
579    }
580}
581
582impl ExitCode {
583    pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
584    pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
585
586    #[inline]
587    pub fn as_i32(&self) -> i32 {
588        self.0 as i32
589    }
590}
591
592impl From<u8> for ExitCode {
593    fn from(code: u8) -> Self {
594        Self(code)
595    }
596}
597
598pub struct CommandArgs<'a> {
599    iter: CStringIter<'a>,
600}
601
602impl<'a> Iterator for CommandArgs<'a> {
603    type Item = &'a OsStr;
604
605    fn next(&mut self) -> Option<&'a OsStr> {
606        self.iter.next().map(|cs| OsStr::from_bytes(cs.to_bytes()))
607    }
608
609    fn size_hint(&self) -> (usize, Option<usize>) {
610        self.iter.size_hint()
611    }
612}
613
614impl<'a> ExactSizeIterator for CommandArgs<'a> {
615    fn len(&self) -> usize {
616        self.iter.len()
617    }
618
619    fn is_empty(&self) -> bool {
620        self.iter.is_empty()
621    }
622}
623
624impl<'a> fmt::Debug for CommandArgs<'a> {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        f.debug_list().entries(self.iter.clone()).finish()
627    }
628}
629
630pub type ChildPipe = crate::sys::pipe::Pipe;
631
632pub fn read_output(
633    out: ChildPipe,
634    stdout: &mut Vec<u8>,
635    err: ChildPipe,
636    stderr: &mut Vec<u8>,
637) -> io::Result<()> {
638    // Set both pipes into nonblocking mode as we're gonna be reading from both
639    // in the `select` loop below, and we wouldn't want one to block the other!
640    out.set_nonblocking(true)?;
641    err.set_nonblocking(true)?;
642
643    let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
644    fds[0].fd = out.as_raw_fd();
645    fds[0].events = libc::POLLIN;
646    fds[1].fd = err.as_raw_fd();
647    fds[1].events = libc::POLLIN;
648    loop {
649        // wait for either pipe to become readable using `poll`
650        cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?;
651
652        if fds[0].revents != 0 && read(&out, stdout)? {
653            err.set_nonblocking(false)?;
654            return err.read_to_end(stderr).map(drop);
655        }
656        if fds[1].revents != 0 && read(&err, stderr)? {
657            out.set_nonblocking(false)?;
658            return out.read_to_end(stdout).map(drop);
659        }
660    }
661
662    // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
663    // EAGAIN. If we hit EOF, then this will happen because the underlying
664    // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
665    // this case we flip the other fd back into blocking mode and read
666    // whatever's leftover on that file descriptor.
667    fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> {
668        match fd.read_to_end(dst) {
669            Ok(_) => Ok(true),
670            Err(e) => {
671                if e.raw_os_error() == Some(libc::EWOULDBLOCK)
672                    || e.raw_os_error() == Some(libc::EAGAIN)
673                {
674                    Ok(false)
675                } else {
676                    Err(e)
677                }
678            }
679        }
680    }
681}