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