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