std/sys/pal/unix/process/
process_common.rs

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