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