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