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