1 // Copyright (c) 2010 Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // The ExceptionHandler object installs signal handlers for a number of
31 // signals. We rely on the signal handler running on the thread which crashed
32 // in order to identify it. This is true of the synchronous signals (SEGV etc),
33 // but not true of ABRT. Thus, if you send ABRT to yourself in a program which
34 // uses ExceptionHandler, you need to use tgkill to direct it to the current
35 // thread.
36 //
37 // The signal flow looks like this:
38 //
39 //   SignalHandler (uses a global stack of ExceptionHandler objects to find
40 //        |         one to handle the signal. If the first rejects it, try
41 //        |         the second etc...)
42 //        V
43 //   HandleSignal ----------------------------| (clones a new process which
44 //        |                                   |  shares an address space with
45 //   (wait for cloned                         |  the crashed process. This
46 //     process)                               |  allows us to ptrace the crashed
47 //        |                                   |  process)
48 //        V                                   V
49 //   (set signal handler to             ThreadEntry (static function to bounce
50 //    SIG_DFL and rethrow,                    |      back into the object)
51 //    killing the crashed                     |
52 //    process)                                V
53 //                                          DoDump  (writes minidump)
54 //                                            |
55 //                                            V
56 //                                         sys_exit
57 //
58 
59 // This code is a little fragmented. Different functions of the ExceptionHandler
60 // class run in a number of different contexts. Some of them run in a normal
61 // context and are easy to code, others run in a compromised context and the
62 // restrictions at the top of minidump_writer.cc apply: no libc and use the
63 // alternative malloc. Each function should have comment above it detailing the
64 // context which it runs in.
65 
66 #include "client/linux/handler/exception_handler.h"
67 
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <linux/limits.h>
71 #include <pthread.h>
72 #include <sched.h>
73 #include <signal.h>
74 #include <stdio.h>
75 #include <sys/mman.h>
76 #include <sys/prctl.h>
77 #include <sys/syscall.h>
78 #include <sys/wait.h>
79 #include <unistd.h>
80 
81 #include <sys/signal.h>
82 #include <sys/ucontext.h>
83 #include <sys/user.h>
84 #include <ucontext.h>
85 
86 #include <algorithm>
87 #include <utility>
88 #include <vector>
89 
90 #include "common/basictypes.h"
91 #include "common/linux/linux_libc_support.h"
92 #include "common/memory.h"
93 #include "client/linux/log/log.h"
94 #include "client/linux/microdump_writer/microdump_writer.h"
95 #include "client/linux/minidump_writer/linux_dumper.h"
96 #include "client/linux/minidump_writer/minidump_writer.h"
97 #include "common/linux/eintr_wrapper.h"
98 #include "third_party/lss/linux_syscall_support.h"
99 
100 #if defined(__ANDROID__)
101 #include "linux/sched.h"
102 #endif
103 
104 #ifndef PR_SET_PTRACER
105 #define PR_SET_PTRACER 0x59616d61
106 #endif
107 
108 // A wrapper for the tgkill syscall: send a signal to a specific thread.
tgkill(pid_t tgid,pid_t tid,int sig)109 static int tgkill(pid_t tgid, pid_t tid, int sig) {
110   return syscall(__NR_tgkill, tgid, tid, sig);
111   return 0;
112 }
113 
114 namespace google_breakpad {
115 
116 namespace {
117 // The list of signals which we consider to be crashes. The default action for
118 // all these signals must be Core (see man 7 signal) because we rethrow the
119 // signal after handling it and expect that it'll be fatal.
120 const int kExceptionSignals[] = {
121   SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGTRAP
122 };
123 const int kNumHandledSignals =
124     sizeof(kExceptionSignals) / sizeof(kExceptionSignals[0]);
125 struct sigaction old_handlers[kNumHandledSignals];
126 bool handlers_installed = false;
127 
128 // InstallAlternateStackLocked will store the newly installed stack in new_stack
129 // and (if it exists) the previously installed stack in old_stack.
130 stack_t old_stack;
131 stack_t new_stack;
132 bool stack_installed = false;
133 
134 // Create an alternative stack to run the signal handlers on. This is done since
135 // the signal might have been caused by a stack overflow.
136 // Runs before crashing: normal context.
InstallAlternateStackLocked()137 void InstallAlternateStackLocked() {
138   if (stack_installed)
139     return;
140 
141   memset(&old_stack, 0, sizeof(old_stack));
142   memset(&new_stack, 0, sizeof(new_stack));
143 
144   // SIGSTKSZ may be too small to prevent the signal handlers from overrunning
145   // the alternative stack. Ensure that the size of the alternative stack is
146   // large enough.
147   static const unsigned kSigStackSize = std::max(16384, SIGSTKSZ);
148 
149   // Only set an alternative stack if there isn't already one, or if the current
150   // one is too small.
151   if (sys_sigaltstack(NULL, &old_stack) == -1 || !old_stack.ss_sp ||
152       old_stack.ss_size < kSigStackSize) {
153     new_stack.ss_sp = calloc(1, kSigStackSize);
154     new_stack.ss_size = kSigStackSize;
155 
156     if (sys_sigaltstack(&new_stack, NULL) == -1) {
157       free(new_stack.ss_sp);
158       return;
159     }
160     stack_installed = true;
161   }
162 }
163 
164 // Runs before crashing: normal context.
RestoreAlternateStackLocked()165 void RestoreAlternateStackLocked() {
166   if (!stack_installed)
167     return;
168 
169   stack_t current_stack;
170   if (sys_sigaltstack(NULL, &current_stack) == -1)
171     return;
172 
173   // Only restore the old_stack if the current alternative stack is the one
174   // installed by the call to InstallAlternateStackLocked.
175   if (current_stack.ss_sp == new_stack.ss_sp) {
176     if (old_stack.ss_sp) {
177       if (sys_sigaltstack(&old_stack, NULL) == -1)
178         return;
179     } else {
180       stack_t disable_stack;
181       disable_stack.ss_flags = SS_DISABLE;
182       if (sys_sigaltstack(&disable_stack, NULL) == -1)
183         return;
184     }
185   }
186 
187   free(new_stack.ss_sp);
188   stack_installed = false;
189 }
190 
InstallDefaultHandler(int sig)191 void InstallDefaultHandler(int sig) {
192 #if defined(__ANDROID__)
193   // Android L+ expose signal and sigaction symbols that override the system
194   // ones. There is a bug in these functions where a request to set the handler
195   // to SIG_DFL is ignored. In that case, an infinite loop is entered as the
196   // signal is repeatedly sent to breakpad's signal handler.
197   // To work around this, directly call the system's sigaction.
198   struct kernel_sigaction sa;
199   memset(&sa, 0, sizeof(sa));
200   sys_sigemptyset(&sa.sa_mask);
201   sa.sa_handler_ = SIG_DFL;
202   sa.sa_flags = SA_RESTART;
203   sys_rt_sigaction(sig, &sa, NULL, sizeof(kernel_sigset_t));
204 #else
205   signal(sig, SIG_DFL);
206 #endif
207 }
208 
209 // The global exception handler stack. This is needed because there may exist
210 // multiple ExceptionHandler instances in a process. Each will have itself
211 // registered in this stack.
212 std::vector<ExceptionHandler*>* g_handler_stack_ = NULL;
213 pthread_mutex_t g_handler_stack_mutex_ = PTHREAD_MUTEX_INITIALIZER;
214 
215 // sizeof(CrashContext) can be too big w.r.t the size of alternatate stack
216 // for SignalHandler(). Keep the crash context as a .bss field. Exception
217 // handlers are serialized by the |g_handler_stack_mutex_| and at most one at a
218 // time can use |g_crash_context_|.
219 ExceptionHandler::CrashContext g_crash_context_;
220 
221 }  // namespace
222 
223 // Runs before crashing: normal context.
ExceptionHandler(const MinidumpDescriptor & descriptor,FilterCallback filter,MinidumpCallback callback,void * callback_context,bool install_handler,const int server_fd)224 ExceptionHandler::ExceptionHandler(const MinidumpDescriptor& descriptor,
225                                    FilterCallback filter,
226                                    MinidumpCallback callback,
227                                    void* callback_context,
228                                    bool install_handler,
229                                    const int server_fd)
230     : filter_(filter),
231       callback_(callback),
232       callback_context_(callback_context),
233       minidump_descriptor_(descriptor),
234       crash_handler_(NULL) {
235   if (server_fd >= 0)
236     crash_generation_client_.reset(CrashGenerationClient::TryCreate(server_fd));
237 
238   if (!IsOutOfProcess() && !minidump_descriptor_.IsFD() &&
239       !minidump_descriptor_.IsMicrodumpOnConsole())
240     minidump_descriptor_.UpdatePath();
241 
242 #if defined(__ANDROID__)
243   if (minidump_descriptor_.IsMicrodumpOnConsole())
244     logger::initializeCrashLogWriter();
245 #endif
246 
247   pthread_mutex_lock(&g_handler_stack_mutex_);
248 
249   // Pre-fault the crash context struct. This is to avoid failing due to OOM
250   // if handling an exception when the process ran out of virtual memory.
251   memset(&g_crash_context_, 0, sizeof(g_crash_context_));
252 
253   if (!g_handler_stack_)
254     g_handler_stack_ = new std::vector<ExceptionHandler*>;
255   if (install_handler) {
256     InstallAlternateStackLocked();
257     InstallHandlersLocked();
258   }
259   g_handler_stack_->push_back(this);
260   pthread_mutex_unlock(&g_handler_stack_mutex_);
261 }
262 
263 // Runs before crashing: normal context.
~ExceptionHandler()264 ExceptionHandler::~ExceptionHandler() {
265   pthread_mutex_lock(&g_handler_stack_mutex_);
266   std::vector<ExceptionHandler*>::iterator handler =
267       std::find(g_handler_stack_->begin(), g_handler_stack_->end(), this);
268   g_handler_stack_->erase(handler);
269   if (g_handler_stack_->empty()) {
270     delete g_handler_stack_;
271     g_handler_stack_ = NULL;
272     RestoreAlternateStackLocked();
273     RestoreHandlersLocked();
274   }
275   pthread_mutex_unlock(&g_handler_stack_mutex_);
276 }
277 
278 // Runs before crashing: normal context.
279 // static
InstallHandlersLocked()280 bool ExceptionHandler::InstallHandlersLocked() {
281   if (handlers_installed)
282     return false;
283 
284   // Fail if unable to store all the old handlers.
285   for (int i = 0; i < kNumHandledSignals; ++i) {
286     if (sigaction(kExceptionSignals[i], NULL, &old_handlers[i]) == -1)
287       return false;
288   }
289 
290   struct sigaction sa;
291   memset(&sa, 0, sizeof(sa));
292   sigemptyset(&sa.sa_mask);
293 
294   // Mask all exception signals when we're handling one of them.
295   for (int i = 0; i < kNumHandledSignals; ++i)
296     sigaddset(&sa.sa_mask, kExceptionSignals[i]);
297 
298   sa.sa_sigaction = SignalHandler;
299   sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
300 
301   for (int i = 0; i < kNumHandledSignals; ++i) {
302     if (sigaction(kExceptionSignals[i], &sa, NULL) == -1) {
303       // At this point it is impractical to back out changes, and so failure to
304       // install a signal is intentionally ignored.
305     }
306   }
307   handlers_installed = true;
308   return true;
309 }
310 
311 // This function runs in a compromised context: see the top of the file.
312 // Runs on the crashing thread.
313 // static
RestoreHandlersLocked()314 void ExceptionHandler::RestoreHandlersLocked() {
315   if (!handlers_installed)
316     return;
317 
318   for (int i = 0; i < kNumHandledSignals; ++i) {
319     if (sigaction(kExceptionSignals[i], &old_handlers[i], NULL) == -1) {
320       InstallDefaultHandler(kExceptionSignals[i]);
321     }
322   }
323   handlers_installed = false;
324 }
325 
326 // void ExceptionHandler::set_crash_handler(HandlerCallback callback) {
327 //   crash_handler_ = callback;
328 // }
329 
330 // This function runs in a compromised context: see the top of the file.
331 // Runs on the crashing thread.
332 // static
SignalHandler(int sig,siginfo_t * info,void * uc)333 void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
334   // All the exception signals are blocked at this point.
335   pthread_mutex_lock(&g_handler_stack_mutex_);
336 
337   // Sometimes, Breakpad runs inside a process where some other buggy code
338   // saves and restores signal handlers temporarily with 'signal'
339   // instead of 'sigaction'. This loses the SA_SIGINFO flag associated
340   // with this function. As a consequence, the values of 'info' and 'uc'
341   // become totally bogus, generally inducing a crash.
342   //
343   // The following code tries to detect this case. When it does, it
344   // resets the signal handlers with sigaction + SA_SIGINFO and returns.
345   // This forces the signal to be thrown again, but this time the kernel
346   // will call the function with the right arguments.
347   struct sigaction cur_handler;
348   if (sigaction(sig, NULL, &cur_handler) == 0 &&
349       (cur_handler.sa_flags & SA_SIGINFO) == 0) {
350     // Reset signal handler with the right flags.
351     sigemptyset(&cur_handler.sa_mask);
352     sigaddset(&cur_handler.sa_mask, sig);
353 
354     cur_handler.sa_sigaction = SignalHandler;
355     cur_handler.sa_flags = SA_ONSTACK | SA_SIGINFO;
356 
357     if (sigaction(sig, &cur_handler, NULL) == -1) {
358       // When resetting the handler fails, try to reset the
359       // default one to avoid an infinite loop here.
360       InstallDefaultHandler(sig);
361     }
362     pthread_mutex_unlock(&g_handler_stack_mutex_);
363     return;
364   }
365 
366   bool handled = false;
367   for (int i = g_handler_stack_->size() - 1; !handled && i >= 0; --i) {
368     handled = (*g_handler_stack_)[i]->HandleSignal(sig, info, uc);
369   }
370 
371   // Upon returning from this signal handler, sig will become unmasked and then
372   // it will be retriggered. If one of the ExceptionHandlers handled it
373   // successfully, restore the default handler. Otherwise, restore the
374   // previously installed handler. Then, when the signal is retriggered, it will
375   // be delivered to the appropriate handler.
376   if (handled) {
377     InstallDefaultHandler(sig);
378   } else {
379     RestoreHandlersLocked();
380   }
381 
382   pthread_mutex_unlock(&g_handler_stack_mutex_);
383 
384   // info->si_code <= 0 iff SI_FROMUSER (SI_FROMKERNEL otherwise).
385   if (info->si_code <= 0 || sig == SIGABRT) {
386     // This signal was triggered by somebody sending us the signal with kill().
387     // In order to retrigger it, we have to queue a new signal by calling
388     // kill() ourselves.  The special case (si_pid == 0 && sig == SIGABRT) is
389     // due to the kernel sending a SIGABRT from a user request via SysRQ.
390     if (tgkill(getpid(), syscall(__NR_gettid), sig) < 0) {
391       // If we failed to kill ourselves (e.g. because a sandbox disallows us
392       // to do so), we instead resort to terminating our process. This will
393       // result in an incorrect exit code.
394       _exit(1);
395     }
396   } else {
397     // This was a synchronous signal triggered by a hard fault (e.g. SIGSEGV).
398     // No need to reissue the signal. It will automatically trigger again,
399     // when we return from the signal handler.
400   }
401 }
402 
403 struct ThreadArgument {
404   pid_t pid;  // the crashing process
405   const MinidumpDescriptor* minidump_descriptor;
406   ExceptionHandler* handler;
407   const void* context;  // a CrashContext structure
408   size_t context_size;
409 };
410 
411 // This is the entry function for the cloned process. We are in a compromised
412 // context here: see the top of the file.
413 // static
ThreadEntry(void * arg)414 int ExceptionHandler::ThreadEntry(void *arg) {
415   const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
416 
417   // Block here until the crashing process unblocks us when
418   // we're allowed to use ptrace
419   thread_arg->handler->WaitForContinueSignal();
420 
421   return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
422                                      thread_arg->context_size) == false;
423 }
424 
425 // This function runs in a compromised context: see the top of the file.
426 // Runs on the crashing thread.
HandleSignal(int sig,siginfo_t * info,void * uc)427 bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
428   if (filter_ && !filter_(callback_context_))
429     return false;
430 
431   // Allow ourselves to be dumped if the signal is trusted.
432   bool signal_trusted = info->si_code > 0;
433   bool signal_pid_trusted = info->si_code == SI_USER ||
434       info->si_code == SI_TKILL;
435   if (signal_trusted || (signal_pid_trusted && info->si_pid == getpid())) {
436     sys_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
437   }
438 
439   // Fill in all the holes in the struct to make Valgrind happy.
440   memset(&g_crash_context_, 0, sizeof(g_crash_context_));
441   memcpy(&g_crash_context_.siginfo, info, sizeof(siginfo_t));
442   memcpy(&g_crash_context_.context, uc, sizeof(struct ucontext));
443 #if defined(__aarch64__)
444   struct ucontext* uc_ptr = (struct ucontext*)uc;
445   struct fpsimd_context* fp_ptr =
446       (struct fpsimd_context*)&uc_ptr->uc_mcontext.__reserved;
447   if (fp_ptr->head.magic == FPSIMD_MAGIC) {
448     memcpy(&g_crash_context_.float_state, fp_ptr,
449            sizeof(g_crash_context_.float_state));
450   }
451 #elif !defined(__ARM_EABI__) && !defined(__mips__)
452   // FP state is not part of user ABI on ARM Linux.
453   // In case of MIPS Linux FP state is already part of struct ucontext
454   // and 'float_state' is not a member of CrashContext.
455   struct ucontext* uc_ptr = (struct ucontext*)uc;
456   if (uc_ptr->uc_mcontext.fpregs) {
457     memcpy(&g_crash_context_.float_state, uc_ptr->uc_mcontext.fpregs,
458            sizeof(g_crash_context_.float_state));
459   }
460 #endif
461   g_crash_context_.tid = syscall(__NR_gettid);
462   if (crash_handler_ != NULL) {
463     if (crash_handler_(&g_crash_context_, sizeof(g_crash_context_),
464                        callback_context_)) {
465       return true;
466     }
467   }
468   return GenerateDump(&g_crash_context_);
469 }
470 
471 // This is a public interface to HandleSignal that allows the client to
472 // generate a crash dump. This function may run in a compromised context.
SimulateSignalDelivery(int sig)473 bool ExceptionHandler::SimulateSignalDelivery(int sig) {
474   siginfo_t siginfo = {};
475   // Mimic a trusted signal to allow tracing the process (see
476   // ExceptionHandler::HandleSignal().
477   siginfo.si_code = SI_USER;
478   siginfo.si_pid = getpid();
479   struct ucontext context;
480   getcontext(&context);
481   return HandleSignal(sig, &siginfo, &context);
482 }
483 
484 // This function may run in a compromised context: see the top of the file.
GenerateDump(CrashContext * context)485 bool ExceptionHandler::GenerateDump(CrashContext *context) {
486   if (IsOutOfProcess())
487     return crash_generation_client_->RequestDump(context, sizeof(*context));
488 
489   // Allocating too much stack isn't a problem, and better to err on the side
490   // of caution than smash it into random locations.
491   static const unsigned kChildStackSize = 16000;
492   PageAllocator allocator;
493   uint8_t* stack = reinterpret_cast<uint8_t*>(allocator.Alloc(kChildStackSize));
494   if (!stack)
495     return false;
496   // clone() needs the top-most address. (scrub just to be safe)
497   stack += kChildStackSize;
498   my_memset(stack - 16, 0, 16);
499 
500   ThreadArgument thread_arg;
501   thread_arg.handler = this;
502   thread_arg.minidump_descriptor = &minidump_descriptor_;
503   thread_arg.pid = getpid();
504   thread_arg.context = context;
505   thread_arg.context_size = sizeof(*context);
506 
507   // We need to explicitly enable ptrace of parent processes on some
508   // kernels, but we need to know the PID of the cloned process before we
509   // can do this. Create a pipe here which we can use to block the
510   // cloned process after creating it, until we have explicitly enabled ptrace
511   if (sys_pipe(fdes) == -1) {
512     // Creating the pipe failed. We'll log an error but carry on anyway,
513     // as we'll probably still get a useful crash report. All that will happen
514     // is the write() and read() calls will fail with EBADF
515     static const char no_pipe_msg[] = "ExceptionHandler::GenerateDump "
516                                       "sys_pipe failed:";
517     logger::write(no_pipe_msg, sizeof(no_pipe_msg) - 1);
518     logger::write(strerror(errno), strlen(strerror(errno)));
519     logger::write("\n", 1);
520 
521     // Ensure fdes[0] and fdes[1] are invalid file descriptors.
522     fdes[0] = fdes[1] = -1;
523   }
524 
525   const pid_t child = sys_clone(
526       ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
527       &thread_arg, NULL, NULL, NULL);
528   if (child == -1) {
529     sys_close(fdes[0]);
530     sys_close(fdes[1]);
531     return false;
532   }
533 
534   // Allow the child to ptrace us
535   sys_prctl(PR_SET_PTRACER, child, 0, 0, 0);
536   SendContinueSignalToChild();
537   int status;
538   const int r = HANDLE_EINTR(sys_waitpid(child, &status, __WALL));
539 
540   sys_close(fdes[0]);
541   sys_close(fdes[1]);
542 
543   if (r == -1) {
544     static const char msg[] = "ExceptionHandler::GenerateDump waitpid failed:";
545     logger::write(msg, sizeof(msg) - 1);
546     logger::write(strerror(errno), strlen(strerror(errno)));
547     logger::write("\n", 1);
548   }
549 
550   bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
551   if (callback_)
552     success = callback_(minidump_descriptor_, callback_context_, success);
553   return success;
554 }
555 
556 // This function runs in a compromised context: see the top of the file.
SendContinueSignalToChild()557 void ExceptionHandler::SendContinueSignalToChild() {
558   static const char okToContinueMessage = 'a';
559   int r;
560   r = HANDLE_EINTR(sys_write(fdes[1], &okToContinueMessage, sizeof(char)));
561   if (r == -1) {
562     static const char msg[] = "ExceptionHandler::SendContinueSignalToChild "
563                               "sys_write failed:";
564     logger::write(msg, sizeof(msg) - 1);
565     logger::write(strerror(errno), strlen(strerror(errno)));
566     logger::write("\n", 1);
567   }
568 }
569 
570 // This function runs in a compromised context: see the top of the file.
571 // Runs on the cloned process.
WaitForContinueSignal()572 void ExceptionHandler::WaitForContinueSignal() {
573   int r;
574   char receivedMessage;
575   r = HANDLE_EINTR(sys_read(fdes[0], &receivedMessage, sizeof(char)));
576   if (r == -1) {
577     static const char msg[] = "ExceptionHandler::WaitForContinueSignal "
578                               "sys_read failed:";
579     logger::write(msg, sizeof(msg) - 1);
580     logger::write(strerror(errno), strlen(strerror(errno)));
581     logger::write("\n", 1);
582   }
583 }
584 
585 // This function runs in a compromised context: see the top of the file.
586 // Runs on the cloned process.
DoDump(pid_t crashing_process,const void * context,size_t context_size)587 bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
588                               size_t context_size) {
589   if (minidump_descriptor_.IsMicrodumpOnConsole()) {
590     return google_breakpad::WriteMicrodump(
591         crashing_process,
592         context,
593         context_size,
594         mapping_list_,
595         *minidump_descriptor_.microdump_extra_info());
596   }
597   if (minidump_descriptor_.IsFD()) {
598     return google_breakpad::WriteMinidump(minidump_descriptor_.fd(),
599                                           minidump_descriptor_.size_limit(),
600                                           crashing_process,
601                                           context,
602                                           context_size,
603                                           mapping_list_,
604                                           app_memory_list_);
605   }
606   return google_breakpad::WriteMinidump(minidump_descriptor_.path(),
607                                         minidump_descriptor_.size_limit(),
608                                         crashing_process,
609                                         context,
610                                         context_size,
611                                         mapping_list_,
612                                         app_memory_list_);
613 }
614 
615 // static
WriteMinidump(const string & dump_path,MinidumpCallback callback,void * callback_context)616 bool ExceptionHandler::WriteMinidump(const string& dump_path,
617                                      MinidumpCallback callback,
618                                      void* callback_context) {
619   MinidumpDescriptor descriptor(dump_path);
620   ExceptionHandler eh(descriptor, NULL, callback, callback_context, false, -1);
621   return eh.WriteMinidump();
622 }
623 
624 // In order to making using EBP to calculate the desired value for ESP
625 // a valid operation, ensure that this function is compiled with a
626 // frame pointer using the following attribute. This attribute
627 // is supported on GCC but not on clang.
628 #if defined(__i386__) && defined(__GNUC__) && !defined(__clang__)
629 __attribute__((optimize("no-omit-frame-pointer")))
630 #endif
WriteMinidump()631 bool ExceptionHandler::WriteMinidump() {
632   if (!IsOutOfProcess() && !minidump_descriptor_.IsFD() &&
633       !minidump_descriptor_.IsMicrodumpOnConsole()) {
634     // Update the path of the minidump so that this can be called multiple times
635     // and new files are created for each minidump.  This is done before the
636     // generation happens, as clients may want to access the MinidumpDescriptor
637     // after this call to find the exact path to the minidump file.
638     minidump_descriptor_.UpdatePath();
639   } else if (minidump_descriptor_.IsFD()) {
640     // Reposition the FD to its beginning and resize it to get rid of the
641     // previous minidump info.
642     lseek(minidump_descriptor_.fd(), 0, SEEK_SET);
643     ignore_result(ftruncate(minidump_descriptor_.fd(), 0));
644   }
645 
646   // Allow this process to be dumped.
647   sys_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
648 
649   CrashContext context;
650   int getcontext_result = getcontext(&context.context);
651   if (getcontext_result)
652     return false;
653 
654 #if defined(__i386__)
655   // In CPUFillFromUContext in minidumpwriter.cc the stack pointer is retrieved
656   // from REG_UESP instead of from REG_ESP. REG_UESP is the user stack pointer
657   // and it only makes sense when running in kernel mode with a different stack
658   // pointer. When WriteMiniDump is called during normal processing REG_UESP is
659   // zero which leads to bad minidump files.
660   if (!context.context.uc_mcontext.gregs[REG_UESP]) {
661     // If REG_UESP is set to REG_ESP then that includes the stack space for the
662     // CrashContext object in this function, which is about 128 KB. Since the
663     // Linux dumper only records 32 KB of stack this would mean that nothing
664     // useful would be recorded. A better option is to set REG_UESP to REG_EBP,
665     // perhaps with a small negative offset in case there is any code that
666     // objects to them being equal.
667     context.context.uc_mcontext.gregs[REG_UESP] =
668       context.context.uc_mcontext.gregs[REG_EBP] - 16;
669     // The stack saving is based off of REG_ESP so it must be set to match the
670     // new REG_UESP.
671     context.context.uc_mcontext.gregs[REG_ESP] =
672       context.context.uc_mcontext.gregs[REG_UESP];
673   }
674 #endif
675 
676 #if !defined(__ARM_EABI__) && !defined(__aarch64__) && !defined(__mips__)
677   // FPU state is not part of ARM EABI ucontext_t.
678   memcpy(&context.float_state, context.context.uc_mcontext.fpregs,
679          sizeof(context.float_state));
680 #endif
681   context.tid = sys_gettid();
682 
683   // Add an exception stream to the minidump for better reporting.
684   memset(&context.siginfo, 0, sizeof(context.siginfo));
685   context.siginfo.si_signo = MD_EXCEPTION_CODE_LIN_DUMP_REQUESTED;
686 #if defined(__i386__)
687   context.siginfo.si_addr =
688       reinterpret_cast<void*>(context.context.uc_mcontext.gregs[REG_EIP]);
689 #elif defined(__x86_64__)
690   context.siginfo.si_addr =
691       reinterpret_cast<void*>(context.context.uc_mcontext.gregs[REG_RIP]);
692 #elif defined(__arm__)
693   context.siginfo.si_addr =
694       reinterpret_cast<void*>(context.context.uc_mcontext.arm_pc);
695 #elif defined(__aarch64__)
696   context.siginfo.si_addr =
697       reinterpret_cast<void*>(context.context.uc_mcontext.pc);
698 #elif defined(__mips__)
699   context.siginfo.si_addr =
700       reinterpret_cast<void*>(context.context.uc_mcontext.pc);
701 #else
702 #error "This code has not been ported to your platform yet."
703 #endif
704 
705   return GenerateDump(&context);
706 }
707 
AddMappingInfo(const string & name,const uint8_t identifier[sizeof (MDGUID)],uintptr_t start_address,size_t mapping_size,size_t file_offset)708 void ExceptionHandler::AddMappingInfo(const string& name,
709                                       const uint8_t identifier[sizeof(MDGUID)],
710                                       uintptr_t start_address,
711                                       size_t mapping_size,
712                                       size_t file_offset) {
713   MappingInfo info;
714   info.start_addr = start_address;
715   info.size = mapping_size;
716   info.offset = file_offset;
717   strncpy(info.name, name.c_str(), sizeof(info.name) - 1);
718   info.name[sizeof(info.name) - 1] = '\0';
719 
720   MappingEntry mapping;
721   mapping.first = info;
722   memcpy(mapping.second, identifier, sizeof(MDGUID));
723   mapping_list_.push_back(mapping);
724 }
725 
RegisterAppMemory(void * ptr,size_t length)726 void ExceptionHandler::RegisterAppMemory(void* ptr, size_t length) {
727   AppMemoryList::iterator iter =
728     std::find(app_memory_list_.begin(), app_memory_list_.end(), ptr);
729   if (iter != app_memory_list_.end()) {
730     // Don't allow registering the same pointer twice.
731     return;
732   }
733 
734   AppMemory app_memory;
735   app_memory.ptr = ptr;
736   app_memory.length = length;
737   app_memory_list_.push_back(app_memory);
738 }
739 
UnregisterAppMemory(void * ptr)740 void ExceptionHandler::UnregisterAppMemory(void* ptr) {
741   AppMemoryList::iterator iter =
742     std::find(app_memory_list_.begin(), app_memory_list_.end(), ptr);
743   if (iter != app_memory_list_.end()) {
744     app_memory_list_.erase(iter);
745   }
746 }
747 
748 // static
WriteMinidumpForChild(pid_t child,pid_t child_blamed_thread,const string & dump_path,MinidumpCallback callback,void * callback_context)749 bool ExceptionHandler::WriteMinidumpForChild(pid_t child,
750                                              pid_t child_blamed_thread,
751                                              const string& dump_path,
752                                              MinidumpCallback callback,
753                                              void* callback_context) {
754   // This function is not run in a compromised context.
755   MinidumpDescriptor descriptor(dump_path);
756   descriptor.UpdatePath();
757   if (!google_breakpad::WriteMinidump(descriptor.path(),
758                                       child,
759                                       child_blamed_thread))
760       return false;
761 
762   return callback ? callback(descriptor, callback_context, true) : true;
763 }
764 
765 }  // namespace google_breakpad
766