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::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    setsid: bool,
102}
103
104// passed back to std::process with the pipes connected to the child, if any
105// were requested
106pub struct StdioPipes {
107    pub stdin: Option<AnonPipe>,
108    pub stdout: Option<AnonPipe>,
109    pub stderr: Option<AnonPipe>,
110}
111
112// passed to do_exec() with configuration of what the child stdio should look
113// like
114#[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    // On Fuchsia, null stdio is the default, so we simply don't specify
127    // any actions at the time of spawning.
128    #[cfg(target_os = "fuchsia")]
129    Null,
130}
131
132#[derive(Debug)]
133pub enum Stdio {
134    Inherit,
135    Null,
136    MakePipe,
137    Fd(FileDesc),
138    StaticFd(BorrowedFd<'static>),
139}
140
141#[derive(Copy, Clone, Debug, Eq, PartialEq)]
142pub enum ProgramKind {
143    /// A program that would be looked up on the PATH (e.g. `ls`)
144    PathLookup,
145    /// A relative path (e.g. `my-dir/foo`, `../foo`, `./foo`)
146    Relative,
147    /// An absolute path.
148    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            // If the program has more than one component in it, it is a relative path.
157            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        // Set a new arg0
195        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        // argv[0] contains the program name, but we are only interested in the
261        // arguments so skip it.
262        iter.next();
263        CommandArgs { iter }
264    }
265
266    pub fn get_envs(&self) -> CommandEnvs<'_> {
267        self.env.iter()
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<AnonPipe>)> {
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::anon_pipe()?;
422                let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
423                Ok((ChildStdio::Owned(theirs.into_inner()), 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<AnonPipe> for Stdio {
442    fn from(pipe: AnonPipe) -> Stdio {
443        Stdio::Fd(pipe.into_inner())
444    }
445}
446
447impl From<FileDesc> for Stdio {
448    fn from(fd: FileDesc) -> Stdio {
449        Stdio::Fd(fd)
450    }
451}
452
453impl From<File> for Stdio {
454    fn from(file: File) -> Stdio {
455        Stdio::Fd(file.into_inner())
456    }
457}
458
459impl From<io::Stdout> for Stdio {
460    fn from(_: io::Stdout) -> Stdio {
461        // This ought really to be is Stdio::StaticFd(input_argument.as_fd()).
462        // But AsFd::as_fd takes its argument by reference, and yields
463        // a bounded lifetime, so it's no use here. There is no AsStaticFd.
464        //
465        // Additionally AsFd is only implemented for the *locked* versions.
466        // We don't want to lock them here.  (The implications of not locking
467        // are the same as those for process::Stdio::inherit().)
468        //
469        // Arguably the hypothetical AsStaticFd and AsFd<'static>
470        // should be implemented for io::Stdout, not just for StdoutLocked.
471        Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) })
472    }
473}
474
475impl From<io::Stderr> for Stdio {
476    fn from(_: io::Stderr) -> Stdio {
477        Stdio::StaticFd(unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) })
478    }
479}
480
481impl ChildStdio {
482    pub fn fd(&self) -> Option<c_int> {
483        match *self {
484            ChildStdio::Inherit => None,
485            ChildStdio::Explicit(fd) => Some(fd),
486            ChildStdio::Owned(ref fd) => Some(fd.as_raw_fd()),
487
488            #[cfg(target_os = "fuchsia")]
489            ChildStdio::Null => None,
490        }
491    }
492}
493
494impl fmt::Debug for Command {
495    // show all attributes but `self.closures` which does not implement `Debug`
496    // and `self.argv` which is not useful for debugging
497    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498        if f.alternate() {
499            let mut debug_command = f.debug_struct("Command");
500            debug_command.field("program", &self.program).field("args", &self.args);
501            if !self.env.is_unchanged() {
502                debug_command.field("env", &self.env);
503            }
504
505            if self.cwd.is_some() {
506                debug_command.field("cwd", &self.cwd);
507            }
508            if self.uid.is_some() {
509                debug_command.field("uid", &self.uid);
510            }
511            if self.gid.is_some() {
512                debug_command.field("gid", &self.gid);
513            }
514
515            if self.groups.is_some() {
516                debug_command.field("groups", &self.groups);
517            }
518
519            if self.stdin.is_some() {
520                debug_command.field("stdin", &self.stdin);
521            }
522            if self.stdout.is_some() {
523                debug_command.field("stdout", &self.stdout);
524            }
525            if self.stderr.is_some() {
526                debug_command.field("stderr", &self.stderr);
527            }
528            if self.pgroup.is_some() {
529                debug_command.field("pgroup", &self.pgroup);
530            }
531
532            #[cfg(target_os = "linux")]
533            {
534                debug_command.field("create_pidfd", &self.create_pidfd);
535            }
536
537            debug_command.finish()
538        } else {
539            if let Some(ref cwd) = self.cwd {
540                write!(f, "cd {cwd:?} && ")?;
541            }
542            if self.env.does_clear() {
543                write!(f, "env -i ")?;
544                // Altered env vars will be printed next, that should exactly work as expected.
545            } else {
546                // Removed env vars need the command to be wrapped in `env`.
547                let mut any_removed = false;
548                for (key, value_opt) in self.get_envs() {
549                    if value_opt.is_none() {
550                        if !any_removed {
551                            write!(f, "env ")?;
552                            any_removed = true;
553                        }
554                        write!(f, "-u {} ", key.to_string_lossy())?;
555                    }
556                }
557            }
558            // Altered env vars can just be added in front of the program.
559            for (key, value_opt) in self.get_envs() {
560                if let Some(value) = value_opt {
561                    write!(f, "{}={value:?} ", key.to_string_lossy())?;
562                }
563            }
564
565            if *self.program != self.args[0] {
566                write!(f, "[{:?}] ", self.program)?;
567            }
568            write!(f, "{:?}", &self.args[0])?;
569
570            for arg in self.get_args() {
571                write!(f, " {:?}", arg)?;
572            }
573
574            Ok(())
575        }
576    }
577}
578
579#[derive(PartialEq, Eq, Clone, Copy)]
580pub struct ExitCode(u8);
581
582impl fmt::Debug for ExitCode {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        f.debug_tuple("unix_exit_status").field(&self.0).finish()
585    }
586}
587
588impl ExitCode {
589    pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
590    pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
591
592    #[inline]
593    pub fn as_i32(&self) -> i32 {
594        self.0 as i32
595    }
596}
597
598impl From<u8> for ExitCode {
599    fn from(code: u8) -> Self {
600        Self(code)
601    }
602}
603
604pub struct CommandArgs<'a> {
605    iter: CStringIter<'a>,
606}
607
608impl<'a> Iterator for CommandArgs<'a> {
609    type Item = &'a OsStr;
610
611    fn next(&mut self) -> Option<&'a OsStr> {
612        self.iter.next().map(|cs| OsStr::from_bytes(cs.to_bytes()))
613    }
614
615    fn size_hint(&self) -> (usize, Option<usize>) {
616        self.iter.size_hint()
617    }
618}
619
620impl<'a> ExactSizeIterator for CommandArgs<'a> {
621    fn len(&self) -> usize {
622        self.iter.len()
623    }
624
625    fn is_empty(&self) -> bool {
626        self.iter.is_empty()
627    }
628}
629
630impl<'a> fmt::Debug for CommandArgs<'a> {
631    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
632        f.debug_list().entries(self.iter.clone()).finish()
633    }
634}