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