]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/redox/process.rs
Rollup merge of #58370 - nox:relax-bounds, r=dtolnay
[rust.git] / src / libstd / sys / redox / process.rs
1 use env::{split_paths};
2 use ffi::{CStr, OsStr};
3 use fmt;
4 use fs::File;
5 use io::{self, prelude::*, BufReader, Error, ErrorKind, SeekFrom};
6 use libc::{EXIT_SUCCESS, EXIT_FAILURE};
7 use os::unix::ffi::OsStrExt;
8 use path::{Path, PathBuf};
9 use ptr;
10 use sys::ext::fs::MetadataExt;
11 use sys::ext::io::AsRawFd;
12 use sys::fd::FileDesc;
13 use sys::fs::{File as SysFile, OpenOptions};
14 use sys::os::{ENV_LOCK, environ};
15 use sys::pipe::{self, AnonPipe};
16 use sys::{cvt, syscall};
17 use sys_common::process::{CommandEnv, DefaultEnvKey};
18
19 ////////////////////////////////////////////////////////////////////////////////
20 // Command
21 ////////////////////////////////////////////////////////////////////////////////
22
23 pub struct Command {
24     // Currently we try hard to ensure that the call to `.exec()` doesn't
25     // actually allocate any memory. While many platforms try to ensure that
26     // memory allocation works after a fork in a multithreaded process, it's
27     // been observed to be buggy and somewhat unreliable, so we do our best to
28     // just not do it at all!
29     //
30     // Along those lines, the `argv` and `envp` raw pointers here are exactly
31     // what's gonna get passed to `execvp`. The `argv` array starts with the
32     // `program` and ends with a NULL, and the `envp` pointer, if present, is
33     // also null-terminated.
34     //
35     // Right now we don't support removing arguments, so there's no much fancy
36     // support there, but we support adding and removing environment variables,
37     // so a side table is used to track where in the `envp` array each key is
38     // located. Whenever we add a key we update it in place if it's already
39     // present, and whenever we remove a key we update the locations of all
40     // other keys.
41     program: String,
42     args: Vec<String>,
43     env: CommandEnv<DefaultEnvKey>,
44
45     cwd: Option<String>,
46     uid: Option<u32>,
47     gid: Option<u32>,
48     saw_nul: bool,
49     closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
50     stdin: Option<Stdio>,
51     stdout: Option<Stdio>,
52     stderr: Option<Stdio>,
53 }
54
55 // passed back to std::process with the pipes connected to the child, if any
56 // were requested
57 pub struct StdioPipes {
58     pub stdin: Option<AnonPipe>,
59     pub stdout: Option<AnonPipe>,
60     pub stderr: Option<AnonPipe>,
61 }
62
63 // passed to do_exec() with configuration of what the child stdio should look
64 // like
65 struct ChildPipes {
66     stdin: ChildStdio,
67     stdout: ChildStdio,
68     stderr: ChildStdio,
69 }
70
71 enum ChildStdio {
72     Inherit,
73     Explicit(usize),
74     Owned(FileDesc),
75 }
76
77 pub enum Stdio {
78     Inherit,
79     Null,
80     MakePipe,
81     Fd(FileDesc),
82 }
83
84 impl Command {
85     pub fn new(program: &OsStr) -> Command {
86         Command {
87             program: program.to_str().unwrap().to_owned(),
88             args: Vec::new(),
89             env: Default::default(),
90             cwd: None,
91             uid: None,
92             gid: None,
93             saw_nul: false,
94             closures: Vec::new(),
95             stdin: None,
96             stdout: None,
97             stderr: None,
98         }
99     }
100
101     pub fn arg(&mut self, arg: &OsStr) {
102         self.args.push(arg.to_str().unwrap().to_owned());
103     }
104
105     pub fn env_mut(&mut self) -> &mut CommandEnv<DefaultEnvKey> {
106         &mut self.env
107     }
108
109     pub fn cwd(&mut self, dir: &OsStr) {
110         self.cwd = Some(dir.to_str().unwrap().to_owned());
111     }
112     pub fn uid(&mut self, id: u32) {
113         self.uid = Some(id);
114     }
115     pub fn gid(&mut self, id: u32) {
116         self.gid = Some(id);
117     }
118
119     pub unsafe fn pre_exec(
120         &mut self,
121         f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
122     ) {
123         self.closures.push(f);
124     }
125
126     pub fn stdin(&mut self, stdin: Stdio) {
127         self.stdin = Some(stdin);
128     }
129     pub fn stdout(&mut self, stdout: Stdio) {
130         self.stdout = Some(stdout);
131     }
132     pub fn stderr(&mut self, stderr: Stdio) {
133         self.stderr = Some(stderr);
134     }
135
136     pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
137                  -> io::Result<(Process, StdioPipes)> {
138          const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX";
139
140          if self.saw_nul {
141              return Err(io::Error::new(ErrorKind::InvalidInput,
142                                        "nul byte found in provided data"));
143          }
144
145          let (ours, theirs) = self.setup_io(default, needs_stdin)?;
146          let (input, output) = pipe::anon_pipe()?;
147
148          let pid = unsafe {
149              match cvt(syscall::clone(0))? {
150                  0 => {
151                      drop(input);
152                      let err = self.do_exec(theirs);
153                      let errno = err.raw_os_error().unwrap_or(syscall::EINVAL) as u32;
154                      let bytes = [
155                          (errno >> 24) as u8,
156                          (errno >> 16) as u8,
157                          (errno >>  8) as u8,
158                          (errno >>  0) as u8,
159                          CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
160                          CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
161                      ];
162                      // pipe I/O up to PIPE_BUF bytes should be atomic, and then
163                      // we want to be sure we *don't* run at_exit destructors as
164                      // we're being torn down regardless
165                      assert!(output.write(&bytes).is_ok());
166                      let _ = syscall::exit(1);
167                      panic!("failed to exit");
168                  }
169                  n => n,
170              }
171          };
172
173          let mut p = Process { pid: pid, status: None };
174          drop(output);
175          let mut bytes = [0; 8];
176
177          // loop to handle EINTR
178          loop {
179              match input.read(&mut bytes) {
180                  Ok(0) => return Ok((p, ours)),
181                  Ok(8) => {
182                      assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
183                              "Validation on the CLOEXEC pipe failed: {:?}", bytes);
184                      let errno = combine(&bytes[0.. 4]);
185                      assert!(p.wait().is_ok(),
186                              "wait() should either return Ok or panic");
187                      return Err(Error::from_raw_os_error(errno))
188                  }
189                  Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
190                  Err(e) => {
191                      assert!(p.wait().is_ok(),
192                              "wait() should either return Ok or panic");
193                      panic!("the CLOEXEC pipe failed: {:?}", e)
194                  },
195                  Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
196                      assert!(p.wait().is_ok(),
197                              "wait() should either return Ok or panic");
198                      panic!("short read on the CLOEXEC pipe")
199                  }
200              }
201          }
202
203          fn combine(arr: &[u8]) -> i32 {
204              let a = arr[0] as u32;
205              let b = arr[1] as u32;
206              let c = arr[2] as u32;
207              let d = arr[3] as u32;
208
209              ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
210          }
211     }
212
213     pub fn exec(&mut self, default: Stdio) -> io::Error {
214         if self.saw_nul {
215             return io::Error::new(ErrorKind::InvalidInput,
216                                   "nul byte found in provided data")
217         }
218
219         match self.setup_io(default, true) {
220             Ok((_, theirs)) => unsafe { self.do_exec(theirs) },
221             Err(e) => e,
222         }
223     }
224
225     // And at this point we've reached a special time in the life of the
226     // child. The child must now be considered hamstrung and unable to
227     // do anything other than syscalls really. Consider the following
228     // scenario:
229     //
230     //      1. Thread A of process 1 grabs the malloc() mutex
231     //      2. Thread B of process 1 forks(), creating thread C
232     //      3. Thread C of process 2 then attempts to malloc()
233     //      4. The memory of process 2 is the same as the memory of
234     //         process 1, so the mutex is locked.
235     //
236     // This situation looks a lot like deadlock, right? It turns out
237     // that this is what pthread_atfork() takes care of, which is
238     // presumably implemented across platforms. The first thing that
239     // threads to *before* forking is to do things like grab the malloc
240     // mutex, and then after the fork they unlock it.
241     //
242     // Despite this information, libnative's spawn has been witnessed to
243     // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
244     // all collected backtraces point at malloc/free traffic in the
245     // child spawned process.
246     //
247     // For this reason, the block of code below should contain 0
248     // invocations of either malloc of free (or their related friends).
249     //
250     // As an example of not having malloc/free traffic, we don't close
251     // this file descriptor by dropping the FileDesc (which contains an
252     // allocation). Instead we just close it manually. This will never
253     // have the drop glue anyway because this code never returns (the
254     // child will either exec() or invoke syscall::exit)
255     unsafe fn do_exec(&mut self, stdio: ChildPipes) -> io::Error {
256         macro_rules! t {
257             ($e:expr) => (match $e {
258                 Ok(e) => e,
259                 Err(e) => return e,
260             })
261         }
262
263         if let Some(fd) = stdio.stderr.fd() {
264             t!(cvt(syscall::dup2(fd, 2, &[])));
265             let mut flags = t!(cvt(syscall::fcntl(2, syscall::F_GETFD, 0)));
266             flags &= ! syscall::O_CLOEXEC;
267             t!(cvt(syscall::fcntl(2, syscall::F_SETFD, flags)));
268         }
269         if let Some(fd) = stdio.stdout.fd() {
270             t!(cvt(syscall::dup2(fd, 1, &[])));
271             let mut flags = t!(cvt(syscall::fcntl(1, syscall::F_GETFD, 0)));
272             flags &= ! syscall::O_CLOEXEC;
273             t!(cvt(syscall::fcntl(1, syscall::F_SETFD, flags)));
274         }
275         if let Some(fd) = stdio.stdin.fd() {
276             t!(cvt(syscall::dup2(fd, 0, &[])));
277             let mut flags = t!(cvt(syscall::fcntl(0, syscall::F_GETFD, 0)));
278             flags &= ! syscall::O_CLOEXEC;
279             t!(cvt(syscall::fcntl(0, syscall::F_SETFD, flags)));
280         }
281
282         if let Some(g) = self.gid {
283             t!(cvt(syscall::setregid(g as usize, g as usize)));
284         }
285         if let Some(u) = self.uid {
286             t!(cvt(syscall::setreuid(u as usize, u as usize)));
287         }
288         if let Some(ref cwd) = self.cwd {
289             t!(cvt(syscall::chdir(cwd)));
290         }
291
292         for callback in self.closures.iter_mut() {
293             t!(callback());
294         }
295
296         self.env.apply();
297
298         let program = if self.program.contains(':') || self.program.contains('/') {
299             Some(PathBuf::from(&self.program))
300         } else if let Ok(path_env) = ::env::var("PATH") {
301             let mut program = None;
302             for mut path in split_paths(&path_env) {
303                 path.push(&self.program);
304                 if path.exists() {
305                     program = Some(path);
306                     break;
307                 }
308             }
309             program
310         } else {
311             None
312         };
313
314         let mut file = if let Some(program) = program {
315             t!(File::open(program.as_os_str()))
316         } else {
317             return io::Error::from_raw_os_error(syscall::ENOENT);
318         };
319
320         // Push all the arguments
321         let mut args: Vec<[usize; 2]> = Vec::with_capacity(1 + self.args.len());
322
323         let interpreter = {
324             let mut reader = BufReader::new(&file);
325
326             let mut shebang = [0; 2];
327             let mut read = 0;
328             loop {
329                 match t!(reader.read(&mut shebang[read..])) {
330                     0 => break,
331                     n => read += n,
332                 }
333             }
334
335             if &shebang == b"#!" {
336                 // This is an interpreted script.
337                 // First of all, since we'll be passing another file to
338                 // fexec(), we need to manually check that we have permission
339                 // to execute this file:
340                 let uid = t!(cvt(syscall::getuid()));
341                 let gid = t!(cvt(syscall::getgid()));
342                 let meta = t!(file.metadata());
343
344                 let mode = if uid == meta.uid() as usize {
345                     meta.mode() >> 3*2 & 0o7
346                 } else if gid == meta.gid() as usize {
347                     meta.mode() >> 3*1 & 0o7
348                 } else {
349                     meta.mode() & 0o7
350                 };
351                 if mode & 1 == 0 {
352                     return io::Error::from_raw_os_error(syscall::EPERM);
353                 }
354
355                 // Second of all, we need to actually read which interpreter it wants
356                 let mut interpreter = Vec::new();
357                 t!(reader.read_until(b'\n', &mut interpreter));
358                 // Pop one trailing newline, if any
359                 if interpreter.ends_with(&[b'\n']) {
360                     interpreter.pop().unwrap();
361                 }
362
363                 // FIXME: Here we could just reassign `file` directly, if it
364                 // wasn't for lexical lifetimes. Remove the whole `let
365                 // interpreter = { ... };` hack once NLL lands.
366                 // NOTE: Although DO REMEMBER to make sure the interpreter path
367                 // still lives long enough to reach fexec.
368                 Some(interpreter)
369             } else {
370                 None
371             }
372         };
373         if let Some(ref interpreter) = interpreter {
374             let path: &OsStr = OsStr::from_bytes(&interpreter);
375             file = t!(File::open(path));
376
377             args.push([interpreter.as_ptr() as usize, interpreter.len()]);
378         } else {
379             t!(file.seek(SeekFrom::Start(0)));
380         }
381
382         args.push([self.program.as_ptr() as usize, self.program.len()]);
383         args.extend(self.args.iter().map(|arg| [arg.as_ptr() as usize, arg.len()]));
384
385         // Push all the variables
386         let mut vars: Vec<[usize; 2]> = Vec::new();
387         {
388             let _guard = ENV_LOCK.lock();
389             let mut environ = *environ();
390             while *environ != ptr::null() {
391                 let var = CStr::from_ptr(*environ).to_bytes();
392                 vars.push([var.as_ptr() as usize, var.len()]);
393                 environ = environ.offset(1);
394             }
395         }
396
397         if let Err(err) = syscall::fexec(file.as_raw_fd(), &args, &vars) {
398             io::Error::from_raw_os_error(err.errno as i32)
399         } else {
400             panic!("return from exec without err");
401         }
402     }
403
404
405     fn setup_io(&self, default: Stdio, needs_stdin: bool)
406                 -> io::Result<(StdioPipes, ChildPipes)> {
407         let null = Stdio::Null;
408         let default_stdin = if needs_stdin {&default} else {&null};
409         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
410         let stdout = self.stdout.as_ref().unwrap_or(&default);
411         let stderr = self.stderr.as_ref().unwrap_or(&default);
412         let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
413         let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
414         let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
415         let ours = StdioPipes {
416             stdin: our_stdin,
417             stdout: our_stdout,
418             stderr: our_stderr,
419         };
420         let theirs = ChildPipes {
421             stdin: their_stdin,
422             stdout: their_stdout,
423             stderr: their_stderr,
424         };
425         Ok((ours, theirs))
426     }
427 }
428
429 impl Stdio {
430     fn to_child_stdio(&self, readable: bool)
431                       -> io::Result<(ChildStdio, Option<AnonPipe>)> {
432         match *self {
433             Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
434
435             // Make sure that the source descriptors are not an stdio
436             // descriptor, otherwise the order which we set the child's
437             // descriptors may blow away a descriptor which we are hoping to
438             // save. For example, suppose we want the child's stderr to be the
439             // parent's stdout, and the child's stdout to be the parent's
440             // stderr. No matter which we dup first, the second will get
441             // overwritten prematurely.
442             Stdio::Fd(ref fd) => {
443                 if fd.raw() <= 2 {
444                     Ok((ChildStdio::Owned(fd.duplicate()?), None))
445                 } else {
446                     Ok((ChildStdio::Explicit(fd.raw()), None))
447                 }
448             }
449
450             Stdio::MakePipe => {
451                 let (reader, writer) = pipe::anon_pipe()?;
452                 let (ours, theirs) = if readable {
453                     (writer, reader)
454                 } else {
455                     (reader, writer)
456                 };
457                 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
458             }
459
460             Stdio::Null => {
461                 let mut opts = OpenOptions::new();
462                 opts.read(readable);
463                 opts.write(!readable);
464                 let fd = SysFile::open(Path::new("null:"), &opts)?;
465                 Ok((ChildStdio::Owned(fd.into_fd()), None))
466             }
467         }
468     }
469 }
470
471 impl From<AnonPipe> for Stdio {
472     fn from(pipe: AnonPipe) -> Stdio {
473         Stdio::Fd(pipe.into_fd())
474     }
475 }
476
477 impl From<SysFile> for Stdio {
478     fn from(file: SysFile) -> Stdio {
479         Stdio::Fd(file.into_fd())
480     }
481 }
482
483 impl ChildStdio {
484     fn fd(&self) -> Option<usize> {
485         match *self {
486             ChildStdio::Inherit => None,
487             ChildStdio::Explicit(fd) => Some(fd),
488             ChildStdio::Owned(ref fd) => Some(fd.raw()),
489         }
490     }
491 }
492
493 impl fmt::Debug for Command {
494     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
495         write!(f, "{:?}", self.program)?;
496         for arg in &self.args {
497             write!(f, " {:?}", arg)?;
498         }
499         Ok(())
500     }
501 }
502
503 ////////////////////////////////////////////////////////////////////////////////
504 // Processes
505 ////////////////////////////////////////////////////////////////////////////////
506
507 /// Unix exit statuses
508 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
509 pub struct ExitStatus(i32);
510
511 impl ExitStatus {
512     fn exited(&self) -> bool {
513         self.0 & 0x7F == 0
514     }
515
516     pub fn success(&self) -> bool {
517         self.code() == Some(0)
518     }
519
520     pub fn code(&self) -> Option<i32> {
521         if self.exited() {
522             Some((self.0 >> 8) & 0xFF)
523         } else {
524             None
525         }
526     }
527
528     pub fn signal(&self) -> Option<i32> {
529         if !self.exited() {
530             Some(self.0 & 0x7F)
531         } else {
532             None
533         }
534     }
535 }
536
537 impl From<i32> for ExitStatus {
538     fn from(a: i32) -> ExitStatus {
539         ExitStatus(a)
540     }
541 }
542
543 impl fmt::Display for ExitStatus {
544     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545         if let Some(code) = self.code() {
546             write!(f, "exit code: {}", code)
547         } else {
548             let signal = self.signal().unwrap();
549             write!(f, "signal: {}", signal)
550         }
551     }
552 }
553
554 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
555 pub struct ExitCode(u8);
556
557 impl ExitCode {
558     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
559     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
560
561     pub fn as_i32(&self) -> i32 {
562         self.0 as i32
563     }
564 }
565
566 /// The unique ID of the process (this should never be negative).
567 pub struct Process {
568     pid: usize,
569     status: Option<ExitStatus>,
570 }
571
572 impl Process {
573     pub fn id(&self) -> u32 {
574         self.pid as u32
575     }
576
577     pub fn kill(&mut self) -> io::Result<()> {
578         // If we've already waited on this process then the pid can be recycled
579         // and used for another process, and we probably shouldn't be killing
580         // random processes, so just return an error.
581         if self.status.is_some() {
582             Err(Error::new(ErrorKind::InvalidInput,
583                            "invalid argument: can't kill an exited process"))
584         } else {
585             cvt(syscall::kill(self.pid, syscall::SIGKILL))?;
586             Ok(())
587         }
588     }
589
590     pub fn wait(&mut self) -> io::Result<ExitStatus> {
591         if let Some(status) = self.status {
592             return Ok(status)
593         }
594         let mut status = 0;
595         cvt(syscall::waitpid(self.pid, &mut status, 0))?;
596         self.status = Some(ExitStatus(status as i32));
597         Ok(ExitStatus(status as i32))
598     }
599
600     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
601         if let Some(status) = self.status {
602             return Ok(Some(status))
603         }
604         let mut status = 0;
605         let pid = cvt(syscall::waitpid(self.pid, &mut status, syscall::WNOHANG))?;
606         if pid == 0 {
607             Ok(None)
608         } else {
609             self.status = Some(ExitStatus(status as i32));
610             Ok(Some(ExitStatus(status as i32)))
611         }
612     }
613 }