]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process/process_common.rs
Auto merge of #66675 - GuillaumeGomez:support-anchors-intra-doc-links, r=kinnison
[rust.git] / src / libstd / sys / unix / process / process_common.rs
1 use crate::os::unix::prelude::*;
2
3 use crate::ffi::{OsString, OsStr, CString, CStr};
4 use crate::fmt;
5 use crate::io;
6 use crate::ptr;
7 use crate::sys::fd::FileDesc;
8 use crate::sys::fs::File;
9 use crate::sys::pipe::{self, AnonPipe};
10 use crate::sys_common::process::CommandEnv;
11 use crate::collections::BTreeMap;
12
13 #[cfg(not(target_os = "fuchsia"))]
14 use crate::sys::fs::OpenOptions;
15
16 use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
17
18 cfg_if::cfg_if! {
19     if #[cfg(target_os = "fuchsia")] {
20         // fuchsia doesn't have /dev/null
21     } else if #[cfg(target_os = "redox")] {
22         const DEV_NULL: &'static str = "null:\0";
23     } else {
24         const DEV_NULL: &'static str = "/dev/null\0";
25     }
26 }
27
28 // Android with api less than 21 define sig* functions inline, so it is not
29 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
30 // to support older Android version (independent of libc version).
31 // The following implementations are based on https://git.io/vSkNf
32 cfg_if::cfg_if! {
33     if #[cfg(target_os = "android")] {
34         pub unsafe fn sigemptyset(set: *mut libc::sigset_t) -> libc::c_int {
35             set.write_bytes(0u8, 1);
36             return 0;
37         }
38         #[allow(dead_code)]
39         pub unsafe fn sigaddset(set: *mut libc::sigset_t, signum: libc::c_int) -> libc::c_int {
40             use crate::{slice, mem};
41
42             let raw = slice::from_raw_parts_mut(set as *mut u8, mem::size_of::<libc::sigset_t>());
43             let bit = (signum - 1) as usize;
44             raw[bit / 8] |= 1 << (bit % 8);
45             return 0;
46         }
47     } else {
48         pub use libc::{sigemptyset, sigaddset};
49     }
50 }
51
52 ////////////////////////////////////////////////////////////////////////////////
53 // Command
54 ////////////////////////////////////////////////////////////////////////////////
55
56 pub struct Command {
57     // Currently we try hard to ensure that the call to `.exec()` doesn't
58     // actually allocate any memory. While many platforms try to ensure that
59     // memory allocation works after a fork in a multithreaded process, it's
60     // been observed to be buggy and somewhat unreliable, so we do our best to
61     // just not do it at all!
62     //
63     // Along those lines, the `argv` and `envp` raw pointers here are exactly
64     // what's gonna get passed to `execvp`. The `argv` array starts with the
65     // `program` and ends with a NULL, and the `envp` pointer, if present, is
66     // also null-terminated.
67     //
68     // Right now we don't support removing arguments, so there's no much fancy
69     // support there, but we support adding and removing environment variables,
70     // so a side table is used to track where in the `envp` array each key is
71     // located. Whenever we add a key we update it in place if it's already
72     // present, and whenever we remove a key we update the locations of all
73     // other keys.
74     program: CString,
75     args: Vec<CString>,
76     argv: Argv,
77     env: CommandEnv,
78
79     cwd: Option<CString>,
80     uid: Option<uid_t>,
81     gid: Option<gid_t>,
82     saw_nul: bool,
83     closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
84     stdin: Option<Stdio>,
85     stdout: Option<Stdio>,
86     stderr: Option<Stdio>,
87 }
88
89 // Create a new type for argv, so that we can make it `Send`
90 struct Argv(Vec<*const c_char>);
91
92 // It is safe to make Argv Send, because it contains pointers to memory owned by `Command.args`
93 unsafe impl Send for Argv {}
94
95 // passed back to std::process with the pipes connected to the child, if any
96 // were requested
97 pub struct StdioPipes {
98     pub stdin: Option<AnonPipe>,
99     pub stdout: Option<AnonPipe>,
100     pub stderr: Option<AnonPipe>,
101 }
102
103 // passed to do_exec() with configuration of what the child stdio should look
104 // like
105 pub struct ChildPipes {
106     pub stdin: ChildStdio,
107     pub stdout: ChildStdio,
108     pub stderr: ChildStdio,
109 }
110
111 pub enum ChildStdio {
112     Inherit,
113     Explicit(c_int),
114     Owned(FileDesc),
115
116     // On Fuchsia, null stdio is the default, so we simply don't specify
117     // any actions at the time of spawning.
118     #[cfg(target_os = "fuchsia")]
119     Null,
120 }
121
122 pub enum Stdio {
123     Inherit,
124     Null,
125     MakePipe,
126     Fd(FileDesc),
127 }
128
129 impl Command {
130     pub fn new(program: &OsStr) -> Command {
131         let mut saw_nul = false;
132         let program = os2c(program, &mut saw_nul);
133         Command {
134             argv: Argv(vec![program.as_ptr(), ptr::null()]),
135             args: vec![program.clone()],
136             program,
137             env: Default::default(),
138             cwd: None,
139             uid: None,
140             gid: None,
141             saw_nul,
142             closures: Vec::new(),
143             stdin: None,
144             stdout: None,
145             stderr: None,
146         }
147     }
148
149     pub fn set_arg_0(&mut self, arg: &OsStr) {
150         // Set a new arg0
151         let arg = os2c(arg, &mut self.saw_nul);
152         debug_assert!(self.argv.0.len() > 1);
153         self.argv.0[0] = arg.as_ptr();
154         self.args[0] = arg;
155     }
156
157     pub fn arg(&mut self, arg: &OsStr) {
158         // Overwrite the trailing NULL pointer in `argv` and then add a new null
159         // pointer.
160         let arg = os2c(arg, &mut self.saw_nul);
161         self.argv.0[self.args.len()] = arg.as_ptr();
162         self.argv.0.push(ptr::null());
163
164         // Also make sure we keep track of the owned value to schedule a
165         // destructor for this memory.
166         self.args.push(arg);
167     }
168
169     pub fn cwd(&mut self, dir: &OsStr) {
170         self.cwd = Some(os2c(dir, &mut self.saw_nul));
171     }
172     pub fn uid(&mut self, id: uid_t) {
173         self.uid = Some(id);
174     }
175     pub fn gid(&mut self, id: gid_t) {
176         self.gid = Some(id);
177     }
178
179     pub fn saw_nul(&self) -> bool {
180         self.saw_nul
181     }
182     pub fn get_argv(&self) -> &Vec<*const c_char> {
183         &self.argv.0
184     }
185
186     pub fn get_program(&self) -> &CStr {
187         &*self.program
188     }
189
190     #[allow(dead_code)]
191     pub fn get_cwd(&self) -> &Option<CString> {
192         &self.cwd
193     }
194     #[allow(dead_code)]
195     pub fn get_uid(&self) -> Option<uid_t> {
196         self.uid
197     }
198     #[allow(dead_code)]
199     pub fn get_gid(&self) -> Option<gid_t> {
200         self.gid
201     }
202
203     pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
204         &mut self.closures
205     }
206
207     pub unsafe fn pre_exec(
208         &mut self,
209         f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
210     ) {
211         self.closures.push(f);
212     }
213
214     pub fn stdin(&mut self, stdin: Stdio) {
215         self.stdin = Some(stdin);
216     }
217
218     pub fn stdout(&mut self, stdout: Stdio) {
219         self.stdout = Some(stdout);
220     }
221
222     pub fn stderr(&mut self, stderr: Stdio) {
223         self.stderr = Some(stderr);
224     }
225
226     pub fn env_mut(&mut self) -> &mut CommandEnv {
227         &mut self.env
228     }
229
230     pub fn capture_env(&mut self) -> Option<CStringArray> {
231         let maybe_env = self.env.capture_if_changed();
232         maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
233     }
234     #[allow(dead_code)]
235     pub fn env_saw_path(&self) -> bool {
236         self.env.have_changed_path()
237     }
238
239     pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
240                 -> io::Result<(StdioPipes, ChildPipes)> {
241         let null = Stdio::Null;
242         let default_stdin = if needs_stdin {&default} else {&null};
243         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
244         let stdout = self.stdout.as_ref().unwrap_or(&default);
245         let stderr = self.stderr.as_ref().unwrap_or(&default);
246         let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
247         let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
248         let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
249         let ours = StdioPipes {
250             stdin: our_stdin,
251             stdout: our_stdout,
252             stderr: our_stderr,
253         };
254         let theirs = ChildPipes {
255             stdin: their_stdin,
256             stdout: their_stdout,
257             stderr: their_stderr,
258         };
259         Ok((ours, theirs))
260     }
261 }
262
263 fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
264     CString::new(s.as_bytes()).unwrap_or_else(|_e| {
265         *saw_nul = true;
266         CString::new("<string-with-nul>").unwrap()
267     })
268 }
269
270 // Helper type to manage ownership of the strings within a C-style array.
271 pub struct CStringArray {
272     items: Vec<CString>,
273     ptrs: Vec<*const c_char>
274 }
275
276 impl CStringArray {
277     pub fn with_capacity(capacity: usize) -> Self {
278         let mut result = CStringArray {
279             items: Vec::with_capacity(capacity),
280             ptrs: Vec::with_capacity(capacity+1)
281         };
282         result.ptrs.push(ptr::null());
283         result
284     }
285     pub fn push(&mut self, item: CString) {
286         let l = self.ptrs.len();
287         self.ptrs[l-1] = item.as_ptr();
288         self.ptrs.push(ptr::null());
289         self.items.push(item);
290     }
291     pub fn as_ptr(&self) -> *const *const c_char {
292         self.ptrs.as_ptr()
293     }
294 }
295
296 fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
297     let mut result = CStringArray::with_capacity(env.len());
298     for (k, v) in env {
299         let mut k: OsString = k.into();
300
301         // Reserve additional space for '=' and null terminator
302         k.reserve_exact(v.len() + 2);
303         k.push("=");
304         k.push(&v);
305
306         // Add the new entry into the array
307         if let Ok(item) = CString::new(k.into_vec()) {
308             result.push(item);
309         } else {
310             *saw_nul = true;
311         }
312     }
313
314     result
315 }
316
317 impl Stdio {
318     pub fn to_child_stdio(&self, readable: bool)
319                       -> io::Result<(ChildStdio, Option<AnonPipe>)> {
320         match *self {
321             Stdio::Inherit => {
322                 Ok((ChildStdio::Inherit, None))
323             },
324
325             // Make sure that the source descriptors are not an stdio
326             // descriptor, otherwise the order which we set the child's
327             // descriptors may blow away a descriptor which we are hoping to
328             // save. For example, suppose we want the child's stderr to be the
329             // parent's stdout, and the child's stdout to be the parent's
330             // stderr. No matter which we dup first, the second will get
331             // overwritten prematurely.
332             Stdio::Fd(ref fd) => {
333                 if fd.raw() >= 0 && fd.raw() <= libc::STDERR_FILENO {
334                     Ok((ChildStdio::Owned(fd.duplicate()?), None))
335                 } else {
336                     Ok((ChildStdio::Explicit(fd.raw()), None))
337                 }
338             }
339
340             Stdio::MakePipe => {
341                 let (reader, writer) = pipe::anon_pipe()?;
342                 let (ours, theirs) = if readable {
343                     (writer, reader)
344                 } else {
345                     (reader, writer)
346                 };
347                 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
348             }
349
350             #[cfg(not(target_os = "fuchsia"))]
351             Stdio::Null => {
352                 let mut opts = OpenOptions::new();
353                 opts.read(readable);
354                 opts.write(!readable);
355                 let path = unsafe {
356                     CStr::from_ptr(DEV_NULL.as_ptr() as *const _)
357                 };
358                 let fd = File::open_c(&path, &opts)?;
359                 Ok((ChildStdio::Owned(fd.into_fd()), None))
360             }
361
362             #[cfg(target_os = "fuchsia")]
363             Stdio::Null => {
364                 Ok((ChildStdio::Null, None))
365             }
366         }
367     }
368 }
369
370 impl From<AnonPipe> for Stdio {
371     fn from(pipe: AnonPipe) -> Stdio {
372         Stdio::Fd(pipe.into_fd())
373     }
374 }
375
376 impl From<File> for Stdio {
377     fn from(file: File) -> Stdio {
378         Stdio::Fd(file.into_fd())
379     }
380 }
381
382 impl ChildStdio {
383     pub fn fd(&self) -> Option<c_int> {
384         match *self {
385             ChildStdio::Inherit => None,
386             ChildStdio::Explicit(fd) => Some(fd),
387             ChildStdio::Owned(ref fd) => Some(fd.raw()),
388
389             #[cfg(target_os = "fuchsia")]
390             ChildStdio::Null => None,
391         }
392     }
393 }
394
395 impl fmt::Debug for Command {
396     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397         write!(f, "{:?}", self.program)?;
398         for arg in &self.args {
399             write!(f, " {:?}", arg)?;
400         }
401         Ok(())
402     }
403 }
404
405 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
406 pub struct ExitCode(u8);
407
408 impl ExitCode {
409     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
410     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
411
412     #[inline]
413     pub fn as_i32(&self) -> i32 {
414         self.0 as i32
415     }
416 }
417
418 #[cfg(all(test, not(target_os = "emscripten")))]
419 mod tests {
420     use super::*;
421
422     use crate::ffi::OsStr;
423     use crate::mem;
424     use crate::ptr;
425     use crate::sys::cvt;
426
427     macro_rules! t {
428         ($e:expr) => {
429             match $e {
430                 Ok(t) => t,
431                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
432             }
433         }
434     }
435
436     // See #14232 for more information, but it appears that signal delivery to a
437     // newly spawned process may just be raced in the macOS, so to prevent this
438     // test from being flaky we ignore it on macOS.
439     #[test]
440     #[cfg_attr(target_os = "macos", ignore)]
441     // When run under our current QEMU emulation test suite this test fails,
442     // although the reason isn't very clear as to why. For now this test is
443     // ignored there.
444     #[cfg_attr(target_arch = "arm", ignore)]
445     #[cfg_attr(target_arch = "aarch64", ignore)]
446     fn test_process_mask() {
447         unsafe {
448             // Test to make sure that a signal mask does not get inherited.
449             let mut cmd = Command::new(OsStr::new("cat"));
450
451             let mut set = mem::MaybeUninit::<libc::sigset_t>::uninit();
452             let mut old_set = mem::MaybeUninit::<libc::sigset_t>::uninit();
453             t!(cvt(sigemptyset(set.as_mut_ptr())));
454             t!(cvt(sigaddset(set.as_mut_ptr(), libc::SIGINT)));
455             t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), old_set.as_mut_ptr())));
456
457             cmd.stdin(Stdio::MakePipe);
458             cmd.stdout(Stdio::MakePipe);
459
460             let (mut cat, mut pipes) = t!(cmd.spawn(Stdio::Null, true));
461             let stdin_write = pipes.stdin.take().unwrap();
462             let stdout_read = pipes.stdout.take().unwrap();
463
464             t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(),
465                                          ptr::null_mut())));
466
467             t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
468             // We need to wait until SIGINT is definitely delivered. The
469             // easiest way is to write something to cat, and try to read it
470             // back: if SIGINT is unmasked, it'll get delivered when cat is
471             // next scheduled.
472             let _ = stdin_write.write(b"Hello");
473             drop(stdin_write);
474
475             // Either EOF or failure (EPIPE) is okay.
476             let mut buf = [0; 5];
477             if let Ok(ret) = stdout_read.read(&mut buf) {
478                 assert_eq!(ret, 0);
479             }
480
481             t!(cat.wait());
482         }
483     }
484 }