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