]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/process/process_unix.rs
Rollup merge of #81309 - lcnr:lazy-norm-err-msgh, r=nikomatsakis
[rust.git] / library / std / src / sys / unix / process / process_unix.rs
1 use crate::convert::TryInto;
2 use crate::fmt;
3 use crate::io::{self, Error, ErrorKind};
4 use crate::ptr;
5 use crate::sys;
6 use crate::sys::cvt;
7 use crate::sys::process::process_common::*;
8
9 #[cfg(target_os = "vxworks")]
10 use libc::RTP_ID as pid_t;
11
12 #[cfg(not(target_os = "vxworks"))]
13 use libc::{c_int, gid_t, pid_t, uid_t};
14
15 ////////////////////////////////////////////////////////////////////////////////
16 // Command
17 ////////////////////////////////////////////////////////////////////////////////
18
19 impl Command {
20     pub fn spawn(
21         &mut self,
22         default: Stdio,
23         needs_stdin: bool,
24     ) -> io::Result<(Process, StdioPipes)> {
25         const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
26
27         let envp = self.capture_env();
28
29         if self.saw_nul() {
30             return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"));
31         }
32
33         let (ours, theirs) = self.setup_io(default, needs_stdin)?;
34
35         if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
36             return Ok((ret, ours));
37         }
38
39         let (input, output) = sys::pipe::anon_pipe()?;
40
41         // Whatever happens after the fork is almost for sure going to touch or
42         // look at the environment in one way or another (PATH in `execvp` or
43         // accessing the `environ` pointer ourselves). Make sure no other thread
44         // is accessing the environment when we do the fork itself.
45         //
46         // Note that as soon as we're done with the fork there's no need to hold
47         // a lock any more because the parent won't do anything and the child is
48         // in its own process.
49         let result = unsafe {
50             let _env_lock = sys::os::env_lock();
51             cvt(libc::fork())?
52         };
53
54         let pid = unsafe {
55             match result {
56                 0 => {
57                     drop(input);
58                     let Err(err) = self.do_exec(theirs, envp.as_ref());
59                     let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
60                     let errno = errno.to_be_bytes();
61                     let bytes = [
62                         errno[0],
63                         errno[1],
64                         errno[2],
65                         errno[3],
66                         CLOEXEC_MSG_FOOTER[0],
67                         CLOEXEC_MSG_FOOTER[1],
68                         CLOEXEC_MSG_FOOTER[2],
69                         CLOEXEC_MSG_FOOTER[3],
70                     ];
71                     // pipe I/O up to PIPE_BUF bytes should be atomic, and then
72                     // we want to be sure we *don't* run at_exit destructors as
73                     // we're being torn down regardless
74                     rtassert!(output.write(&bytes).is_ok());
75                     libc::_exit(1)
76                 }
77                 n => n,
78             }
79         };
80
81         let mut p = Process { pid, status: None };
82         drop(output);
83         let mut bytes = [0; 8];
84
85         // loop to handle EINTR
86         loop {
87             match input.read(&mut bytes) {
88                 Ok(0) => return Ok((p, ours)),
89                 Ok(8) => {
90                     let (errno, footer) = bytes.split_at(4);
91                     assert_eq!(
92                         CLOEXEC_MSG_FOOTER, footer,
93                         "Validation on the CLOEXEC pipe failed: {:?}",
94                         bytes
95                     );
96                     let errno = i32::from_be_bytes(errno.try_into().unwrap());
97                     assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
98                     return Err(Error::from_raw_os_error(errno));
99                 }
100                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
101                 Err(e) => {
102                     assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
103                     panic!("the CLOEXEC pipe failed: {:?}", e)
104                 }
105                 Ok(..) => {
106                     // pipe I/O up to PIPE_BUF bytes should be atomic
107                     assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
108                     panic!("short read on the CLOEXEC pipe")
109                 }
110             }
111         }
112     }
113
114     pub fn exec(&mut self, default: Stdio) -> io::Error {
115         let envp = self.capture_env();
116
117         if self.saw_nul() {
118             return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data");
119         }
120
121         match self.setup_io(default, true) {
122             Ok((_, theirs)) => {
123                 unsafe {
124                     // Similar to when forking, we want to ensure that access to
125                     // the environment is synchronized, so make sure to grab the
126                     // environment lock before we try to exec.
127                     let _lock = sys::os::env_lock();
128
129                     let Err(e) = self.do_exec(theirs, envp.as_ref());
130                     e
131                 }
132             }
133             Err(e) => e,
134         }
135     }
136
137     // And at this point we've reached a special time in the life of the
138     // child. The child must now be considered hamstrung and unable to
139     // do anything other than syscalls really. Consider the following
140     // scenario:
141     //
142     //      1. Thread A of process 1 grabs the malloc() mutex
143     //      2. Thread B of process 1 forks(), creating thread C
144     //      3. Thread C of process 2 then attempts to malloc()
145     //      4. The memory of process 2 is the same as the memory of
146     //         process 1, so the mutex is locked.
147     //
148     // This situation looks a lot like deadlock, right? It turns out
149     // that this is what pthread_atfork() takes care of, which is
150     // presumably implemented across platforms. The first thing that
151     // threads to *before* forking is to do things like grab the malloc
152     // mutex, and then after the fork they unlock it.
153     //
154     // Despite this information, libnative's spawn has been witnessed to
155     // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
156     // all collected backtraces point at malloc/free traffic in the
157     // child spawned process.
158     //
159     // For this reason, the block of code below should contain 0
160     // invocations of either malloc of free (or their related friends).
161     //
162     // As an example of not having malloc/free traffic, we don't close
163     // this file descriptor by dropping the FileDesc (which contains an
164     // allocation). Instead we just close it manually. This will never
165     // have the drop glue anyway because this code never returns (the
166     // child will either exec() or invoke libc::exit)
167     unsafe fn do_exec(
168         &mut self,
169         stdio: ChildPipes,
170         maybe_envp: Option<&CStringArray>,
171     ) -> Result<!, io::Error> {
172         use crate::sys::{self, cvt_r};
173
174         if let Some(fd) = stdio.stdin.fd() {
175             cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
176         }
177         if let Some(fd) = stdio.stdout.fd() {
178             cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
179         }
180         if let Some(fd) = stdio.stderr.fd() {
181             cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
182         }
183
184         #[cfg(not(target_os = "l4re"))]
185         {
186             if let Some(_g) = self.get_groups() {
187                 //FIXME: Redox kernel does not support setgroups yet
188                 #[cfg(not(target_os = "redox"))]
189                 cvt(libc::setgroups(_g.len().try_into().unwrap(), _g.as_ptr()))?;
190             }
191             if let Some(u) = self.get_gid() {
192                 cvt(libc::setgid(u as gid_t))?;
193             }
194             if let Some(u) = self.get_uid() {
195                 // When dropping privileges from root, the `setgroups` call
196                 // will remove any extraneous groups. We only drop groups
197                 // if the current uid is 0 and we weren't given an explicit
198                 // set of groups. If we don't call this, then even though our
199                 // uid has dropped, we may still have groups that enable us to
200                 // do super-user things.
201                 //FIXME: Redox kernel does not support setgroups yet
202                 #[cfg(not(target_os = "redox"))]
203                 if libc::getuid() == 0 && self.get_groups().is_none() {
204                     cvt(libc::setgroups(0, ptr::null()))?;
205                 }
206                 cvt(libc::setuid(u as uid_t))?;
207             }
208         }
209         if let Some(ref cwd) = *self.get_cwd() {
210             cvt(libc::chdir(cwd.as_ptr()))?;
211         }
212
213         // emscripten has no signal support.
214         #[cfg(not(target_os = "emscripten"))]
215         {
216             use crate::mem::MaybeUninit;
217             // Reset signal handling so the child process starts in a
218             // standardized state. libstd ignores SIGPIPE, and signal-handling
219             // libraries often set a mask. Child processes inherit ignored
220             // signals and the signal mask from their parent, but most
221             // UNIX programs do not reset these things on their own, so we
222             // need to clean things up now to avoid confusing the program
223             // we're about to run.
224             let mut set = MaybeUninit::<libc::sigset_t>::uninit();
225             cvt(sigemptyset(set.as_mut_ptr()))?;
226             cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?;
227             let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
228             if ret == libc::SIG_ERR {
229                 return Err(io::Error::last_os_error());
230             }
231         }
232
233         for callback in self.get_closures().iter_mut() {
234             callback()?;
235         }
236
237         // Although we're performing an exec here we may also return with an
238         // error from this function (without actually exec'ing) in which case we
239         // want to be sure to restore the global environment back to what it
240         // once was, ensuring that our temporary override, when free'd, doesn't
241         // corrupt our process's environment.
242         let mut _reset = None;
243         if let Some(envp) = maybe_envp {
244             struct Reset(*const *const libc::c_char);
245
246             impl Drop for Reset {
247                 fn drop(&mut self) {
248                     unsafe {
249                         *sys::os::environ() = self.0;
250                     }
251                 }
252             }
253
254             _reset = Some(Reset(*sys::os::environ()));
255             *sys::os::environ() = envp.as_ptr();
256         }
257
258         libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());
259         Err(io::Error::last_os_error())
260     }
261
262     #[cfg(not(any(
263         target_os = "macos",
264         target_os = "freebsd",
265         all(target_os = "linux", target_env = "gnu"),
266         all(target_os = "linux", target_env = "musl"),
267     )))]
268     fn posix_spawn(
269         &mut self,
270         _: &ChildPipes,
271         _: Option<&CStringArray>,
272     ) -> io::Result<Option<Process>> {
273         Ok(None)
274     }
275
276     // Only support platforms for which posix_spawn() can return ENOENT
277     // directly.
278     #[cfg(any(
279         target_os = "macos",
280         target_os = "freebsd",
281         all(target_os = "linux", target_env = "gnu"),
282         all(target_os = "linux", target_env = "musl"),
283     ))]
284     fn posix_spawn(
285         &mut self,
286         stdio: &ChildPipes,
287         envp: Option<&CStringArray>,
288     ) -> io::Result<Option<Process>> {
289         use crate::mem::MaybeUninit;
290         use crate::sys::{self, cvt_nz};
291
292         if self.get_gid().is_some()
293             || self.get_uid().is_some()
294             || (self.env_saw_path() && !self.program_is_path())
295             || !self.get_closures().is_empty()
296             || self.get_groups().is_some()
297         {
298             return Ok(None);
299         }
300
301         // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
302         #[cfg(all(target_os = "linux", target_env = "gnu"))]
303         {
304             if let Some(version) = sys::os::glibc_version() {
305                 if version < (2, 24) {
306                     return Ok(None);
307                 }
308             } else {
309                 return Ok(None);
310             }
311         }
312
313         // Solaris, glibc 2.29+, and musl 1.24+ can set a new working directory,
314         // and maybe others will gain this non-POSIX function too. We'll check
315         // for this weak symbol as soon as it's needed, so we can return early
316         // otherwise to do a manual chdir before exec.
317         weak! {
318             fn posix_spawn_file_actions_addchdir_np(
319                 *mut libc::posix_spawn_file_actions_t,
320                 *const libc::c_char
321             ) -> libc::c_int
322         }
323         let addchdir = match self.get_cwd() {
324             Some(cwd) => {
325                 if cfg!(target_os = "macos") {
326                     // There is a bug in macOS where a relative executable
327                     // path like "../myprogram" will cause `posix_spawn` to
328                     // successfully launch the program, but erroneously return
329                     // ENOENT when used with posix_spawn_file_actions_addchdir_np
330                     // which was introduced in macOS 10.15.
331                     return Ok(None);
332                 }
333                 match posix_spawn_file_actions_addchdir_np.get() {
334                     Some(f) => Some((f, cwd)),
335                     None => return Ok(None),
336                 }
337             }
338             None => None,
339         };
340
341         let mut p = Process { pid: 0, status: None };
342
343         struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
344
345         impl Drop for PosixSpawnFileActions<'_> {
346             fn drop(&mut self) {
347                 unsafe {
348                     libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
349                 }
350             }
351         }
352
353         struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
354
355         impl Drop for PosixSpawnattr<'_> {
356             fn drop(&mut self) {
357                 unsafe {
358                     libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
359                 }
360             }
361         }
362
363         unsafe {
364             let mut attrs = MaybeUninit::uninit();
365             cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
366             let attrs = PosixSpawnattr(&mut attrs);
367
368             let mut file_actions = MaybeUninit::uninit();
369             cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
370             let file_actions = PosixSpawnFileActions(&mut file_actions);
371
372             if let Some(fd) = stdio.stdin.fd() {
373                 cvt_nz(libc::posix_spawn_file_actions_adddup2(
374                     file_actions.0.as_mut_ptr(),
375                     fd,
376                     libc::STDIN_FILENO,
377                 ))?;
378             }
379             if let Some(fd) = stdio.stdout.fd() {
380                 cvt_nz(libc::posix_spawn_file_actions_adddup2(
381                     file_actions.0.as_mut_ptr(),
382                     fd,
383                     libc::STDOUT_FILENO,
384                 ))?;
385             }
386             if let Some(fd) = stdio.stderr.fd() {
387                 cvt_nz(libc::posix_spawn_file_actions_adddup2(
388                     file_actions.0.as_mut_ptr(),
389                     fd,
390                     libc::STDERR_FILENO,
391                 ))?;
392             }
393             if let Some((f, cwd)) = addchdir {
394                 cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
395             }
396
397             let mut set = MaybeUninit::<libc::sigset_t>::uninit();
398             cvt(sigemptyset(set.as_mut_ptr()))?;
399             cvt_nz(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?;
400             cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?;
401             cvt_nz(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?;
402
403             let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK;
404             cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
405
406             // Make sure we synchronize access to the global `environ` resource
407             let _env_lock = sys::os::env_lock();
408             let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _);
409             cvt_nz(libc::posix_spawnp(
410                 &mut p.pid,
411                 self.get_program_cstr().as_ptr(),
412                 file_actions.0.as_ptr(),
413                 attrs.0.as_ptr(),
414                 self.get_argv().as_ptr() as *const _,
415                 envp as *const _,
416             ))?;
417             Ok(Some(p))
418         }
419     }
420 }
421
422 ////////////////////////////////////////////////////////////////////////////////
423 // Processes
424 ////////////////////////////////////////////////////////////////////////////////
425
426 /// The unique ID of the process (this should never be negative).
427 pub struct Process {
428     pid: pid_t,
429     status: Option<ExitStatus>,
430 }
431
432 impl Process {
433     pub fn id(&self) -> u32 {
434         self.pid as u32
435     }
436
437     pub fn kill(&mut self) -> io::Result<()> {
438         // If we've already waited on this process then the pid can be recycled
439         // and used for another process, and we probably shouldn't be killing
440         // random processes, so just return an error.
441         if self.status.is_some() {
442             Err(Error::new(
443                 ErrorKind::InvalidInput,
444                 "invalid argument: can't kill an exited process",
445             ))
446         } else {
447             cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
448         }
449     }
450
451     pub fn wait(&mut self) -> io::Result<ExitStatus> {
452         use crate::sys::cvt_r;
453         if let Some(status) = self.status {
454             return Ok(status);
455         }
456         let mut status = 0 as c_int;
457         cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
458         self.status = Some(ExitStatus::new(status));
459         Ok(ExitStatus::new(status))
460     }
461
462     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
463         if let Some(status) = self.status {
464             return Ok(Some(status));
465         }
466         let mut status = 0 as c_int;
467         let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
468         if pid == 0 {
469             Ok(None)
470         } else {
471             self.status = Some(ExitStatus::new(status));
472             Ok(Some(ExitStatus::new(status)))
473         }
474     }
475 }
476
477 /// Unix exit statuses
478 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
479 pub struct ExitStatus(c_int);
480
481 impl ExitStatus {
482     pub fn new(status: c_int) -> ExitStatus {
483         ExitStatus(status)
484     }
485
486     fn exited(&self) -> bool {
487         libc::WIFEXITED(self.0)
488     }
489
490     pub fn success(&self) -> bool {
491         self.code() == Some(0)
492     }
493
494     pub fn code(&self) -> Option<i32> {
495         if self.exited() { Some(libc::WEXITSTATUS(self.0)) } else { None }
496     }
497
498     pub fn signal(&self) -> Option<i32> {
499         if libc::WIFSIGNALED(self.0) { Some(libc::WTERMSIG(self.0)) } else { None }
500     }
501
502     pub fn core_dumped(&self) -> bool {
503         libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
504     }
505
506     pub fn stopped_signal(&self) -> Option<i32> {
507         if libc::WIFSTOPPED(self.0) { Some(libc::WSTOPSIG(self.0)) } else { None }
508     }
509
510     pub fn continued(&self) -> bool {
511         libc::WIFCONTINUED(self.0)
512     }
513
514     pub fn into_raw(&self) -> c_int {
515         self.0
516     }
517 }
518
519 /// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
520 impl From<c_int> for ExitStatus {
521     fn from(a: c_int) -> ExitStatus {
522         ExitStatus(a)
523     }
524 }
525
526 impl fmt::Display for ExitStatus {
527     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528         if let Some(code) = self.code() {
529             write!(f, "exit code: {}", code)
530         } else if let Some(signal) = self.signal() {
531             if self.core_dumped() {
532                 write!(f, "signal: {} (core dumped)", signal)
533             } else {
534                 write!(f, "signal: {}", signal)
535             }
536         } else if let Some(signal) = self.stopped_signal() {
537             write!(f, "stopped (not terminated) by signal: {}", signal)
538         } else if self.continued() {
539             write!(f, "continued (WIFCONTINUED)")
540         } else {
541             write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
542         }
543     }
544 }
545
546 #[cfg(test)]
547 #[path = "process_unix/tests.rs"]
548 mod tests;