- add third_party src.
[platform/framework/web/crosswalk.git] / src / breakpad / src / client / linux / handler / exception_handler.cc
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 <sched.h>
72 #include <signal.h>
73 #include <stdio.h>
74 #include <sys/mman.h>
75 #include <sys/prctl.h>
76 #include <sys/syscall.h>
77 #include <sys/wait.h>
78 #include <unistd.h>
79
80 #include <sys/signal.h>
81 #include <sys/ucontext.h>
82 #include <sys/user.h>
83 #include <ucontext.h>
84
85 #include <algorithm>
86 #include <utility>
87 #include <vector>
88
89 #include "common/linux/linux_libc_support.h"
90 #include "common/memory.h"
91 #include "client/linux/log/log.h"
92 #include "client/linux/minidump_writer/linux_dumper.h"
93 #include "client/linux/minidump_writer/minidump_writer.h"
94 #include "common/linux/eintr_wrapper.h"
95 #include "third_party/lss/linux_syscall_support.h"
96
97 #if defined(__ANDROID__)
98 #include "linux/sched.h"
99 #endif
100
101 #ifndef PR_SET_PTRACER
102 #define PR_SET_PTRACER 0x59616d61
103 #endif
104
105 // A wrapper for the tgkill syscall: send a signal to a specific thread.
106 static int tgkill(pid_t tgid, pid_t tid, int sig) {
107   return syscall(__NR_tgkill, tgid, tid, sig);
108   return 0;
109 }
110
111 namespace google_breakpad {
112
113 namespace {
114 // The list of signals which we consider to be crashes. The default action for
115 // all these signals must be Core (see man 7 signal) because we rethrow the
116 // signal after handling it and expect that it'll be fatal.
117 const int kExceptionSignals[] = {
118   SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS
119 };
120 const int kNumHandledSignals =
121     sizeof(kExceptionSignals) / sizeof(kExceptionSignals[0]);
122 struct sigaction old_handlers[kNumHandledSignals];
123 bool handlers_installed = false;
124
125 // InstallAlternateStackLocked will store the newly installed stack in new_stack
126 // and (if it exists) the previously installed stack in old_stack.
127 stack_t old_stack;
128 stack_t new_stack;
129 bool stack_installed = false;
130
131 // Create an alternative stack to run the signal handlers on. This is done since
132 // the signal might have been caused by a stack overflow.
133 // Runs before crashing: normal context.
134 void InstallAlternateStackLocked() {
135   if (stack_installed)
136     return;
137
138   memset(&old_stack, 0, sizeof(old_stack));
139   memset(&new_stack, 0, sizeof(new_stack));
140
141   // SIGSTKSZ may be too small to prevent the signal handlers from overrunning
142   // the alternative stack. Ensure that the size of the alternative stack is
143   // large enough.
144   static const unsigned kSigStackSize = std::max(8192, SIGSTKSZ);
145
146   // Only set an alternative stack if there isn't already one, or if the current
147   // one is too small.
148   if (sys_sigaltstack(NULL, &old_stack) == -1 || !old_stack.ss_sp ||
149       old_stack.ss_size < kSigStackSize) {
150     new_stack.ss_sp = malloc(kSigStackSize);
151     new_stack.ss_size = kSigStackSize;
152
153     if (sys_sigaltstack(&new_stack, NULL) == -1) {
154       free(new_stack.ss_sp);
155       return;
156     }
157     stack_installed = true;
158   }
159 }
160
161 // Runs before crashing: normal context.
162 void RestoreAlternateStackLocked() {
163   if (!stack_installed)
164     return;
165
166   stack_t current_stack;
167   if (sys_sigaltstack(NULL, &current_stack) == -1)
168     return;
169
170   // Only restore the old_stack if the current alternative stack is the one
171   // installed by the call to InstallAlternateStackLocked.
172   if (current_stack.ss_sp == new_stack.ss_sp) {
173     if (old_stack.ss_sp) {
174       if (sys_sigaltstack(&old_stack, NULL) == -1)
175         return;
176     } else {
177       stack_t disable_stack;
178       disable_stack.ss_flags = SS_DISABLE;
179       if (sys_sigaltstack(&disable_stack, NULL) == -1)
180         return;
181     }
182   }
183
184   free(new_stack.ss_sp);
185   stack_installed = false;
186 }
187
188 }  // namespace
189
190 // We can stack multiple exception handlers. In that case, this is the global
191 // which holds the stack.
192 std::vector<ExceptionHandler*>* ExceptionHandler::handler_stack_ = NULL;
193 pthread_mutex_t ExceptionHandler::handler_stack_mutex_ =
194     PTHREAD_MUTEX_INITIALIZER;
195
196 // Runs before crashing: normal context.
197 ExceptionHandler::ExceptionHandler(const MinidumpDescriptor& descriptor,
198                                    FilterCallback filter,
199                                    MinidumpCallback callback,
200                                    void* callback_context,
201                                    bool install_handler,
202                                    const int server_fd)
203     : filter_(filter),
204       callback_(callback),
205       callback_context_(callback_context),
206       minidump_descriptor_(descriptor),
207       crash_handler_(NULL) {
208   if (server_fd >= 0)
209     crash_generation_client_.reset(CrashGenerationClient::TryCreate(server_fd));
210
211   if (!IsOutOfProcess() && !minidump_descriptor_.IsFD())
212     minidump_descriptor_.UpdatePath();
213
214   pthread_mutex_lock(&handler_stack_mutex_);
215   if (!handler_stack_)
216     handler_stack_ = new std::vector<ExceptionHandler*>;
217   if (install_handler) {
218     InstallAlternateStackLocked();
219     InstallHandlersLocked();
220   }
221   handler_stack_->push_back(this);
222   pthread_mutex_unlock(&handler_stack_mutex_);
223 }
224
225 // Runs before crashing: normal context.
226 ExceptionHandler::~ExceptionHandler() {
227   pthread_mutex_lock(&handler_stack_mutex_);
228   std::vector<ExceptionHandler*>::iterator handler =
229       std::find(handler_stack_->begin(), handler_stack_->end(), this);
230   handler_stack_->erase(handler);
231   if (handler_stack_->empty()) {
232     RestoreAlternateStackLocked();
233     RestoreHandlersLocked();
234   }
235   pthread_mutex_unlock(&handler_stack_mutex_);
236 }
237
238 // Runs before crashing: normal context.
239 // static
240 bool ExceptionHandler::InstallHandlersLocked() {
241   if (handlers_installed)
242     return false;
243
244   // Fail if unable to store all the old handlers.
245   for (int i = 0; i < kNumHandledSignals; ++i) {
246     if (sigaction(kExceptionSignals[i], NULL, &old_handlers[i]) == -1)
247       return false;
248   }
249
250   struct sigaction sa;
251   memset(&sa, 0, sizeof(sa));
252   sigemptyset(&sa.sa_mask);
253
254   // Mask all exception signals when we're handling one of them.
255   for (int i = 0; i < kNumHandledSignals; ++i)
256     sigaddset(&sa.sa_mask, kExceptionSignals[i]);
257
258   sa.sa_sigaction = SignalHandler;
259   sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
260
261   for (int i = 0; i < kNumHandledSignals; ++i) {
262     if (sigaction(kExceptionSignals[i], &sa, NULL) == -1) {
263       // At this point it is impractical to back out changes, and so failure to
264       // install a signal is intentionally ignored.
265     }
266   }
267   handlers_installed = true;
268   return true;
269 }
270
271 // This function runs in a compromised context: see the top of the file.
272 // Runs on the crashing thread.
273 // static
274 void ExceptionHandler::RestoreHandlersLocked() {
275   if (!handlers_installed)
276     return;
277
278   for (int i = 0; i < kNumHandledSignals; ++i) {
279     if (sigaction(kExceptionSignals[i], &old_handlers[i], NULL) == -1) {
280       signal(kExceptionSignals[i], SIG_DFL);
281     }
282   }
283   handlers_installed = false;
284 }
285
286 // void ExceptionHandler::set_crash_handler(HandlerCallback callback) {
287 //   crash_handler_ = callback;
288 // }
289
290 // This function runs in a compromised context: see the top of the file.
291 // Runs on the crashing thread.
292 // static
293 void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
294   // All the exception signals are blocked at this point.
295   pthread_mutex_lock(&handler_stack_mutex_);
296
297   // Sometimes, Breakpad runs inside a process where some other buggy code
298   // saves and restores signal handlers temporarily with 'signal'
299   // instead of 'sigaction'. This loses the SA_SIGINFO flag associated
300   // with this function. As a consequence, the values of 'info' and 'uc'
301   // become totally bogus, generally inducing a crash.
302   //
303   // The following code tries to detect this case. When it does, it
304   // resets the signal handlers with sigaction + SA_SIGINFO and returns.
305   // This forces the signal to be thrown again, but this time the kernel
306   // will call the function with the right arguments.
307   struct sigaction cur_handler;
308   if (sigaction(sig, NULL, &cur_handler) == 0 &&
309       (cur_handler.sa_flags & SA_SIGINFO) == 0) {
310     // Reset signal handler with the right flags.
311     sigemptyset(&cur_handler.sa_mask);
312     sigaddset(&cur_handler.sa_mask, sig);
313
314     cur_handler.sa_sigaction = SignalHandler;
315     cur_handler.sa_flags = SA_ONSTACK | SA_SIGINFO;
316
317     if (sigaction(sig, &cur_handler, NULL) == -1) {
318       // When resetting the handler fails, try to reset the
319       // default one to avoid an infinite loop here.
320       signal(sig, SIG_DFL);
321     }
322     pthread_mutex_unlock(&handler_stack_mutex_);
323     return;
324   }
325
326   bool handled = false;
327   for (int i = handler_stack_->size() - 1; !handled && i >= 0; --i) {
328     handled = (*handler_stack_)[i]->HandleSignal(sig, info, uc);
329   }
330
331   // Upon returning from this signal handler, sig will become unmasked and then
332   // it will be retriggered. If one of the ExceptionHandlers handled it
333   // successfully, restore the default handler. Otherwise, restore the
334   // previously installed handler. Then, when the signal is retriggered, it will
335   // be delivered to the appropriate handler.
336   if (handled) {
337     signal(sig, SIG_DFL);
338   } else {
339     RestoreHandlersLocked();
340   }
341
342   pthread_mutex_unlock(&handler_stack_mutex_);
343
344   if (info->si_pid) {
345     // This signal was triggered by somebody sending us the signal with kill().
346     // In order to retrigger it, we have to queue a new signal by calling
347     // kill() ourselves.
348     if (tgkill(getpid(), syscall(__NR_gettid), sig) < 0) {
349       // If we failed to kill ourselves (e.g. because a sandbox disallows us
350       // to do so), we instead resort to terminating our process. This will
351       // result in an incorrect exit code.
352       _exit(1);
353     }
354   } else {
355     // This was a synchronous signal triggered by a hard fault (e.g. SIGSEGV).
356     // No need to reissue the signal. It will automatically trigger again,
357     // when we return from the signal handler.
358   }
359 }
360
361 struct ThreadArgument {
362   pid_t pid;  // the crashing process
363   const MinidumpDescriptor* minidump_descriptor;
364   ExceptionHandler* handler;
365   const void* context;  // a CrashContext structure
366   size_t context_size;
367 };
368
369 // This is the entry function for the cloned process. We are in a compromised
370 // context here: see the top of the file.
371 // static
372 int ExceptionHandler::ThreadEntry(void *arg) {
373   const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
374
375   // Block here until the crashing process unblocks us when
376   // we're allowed to use ptrace
377   thread_arg->handler->WaitForContinueSignal();
378
379   return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
380                                      thread_arg->context_size) == false;
381 }
382
383 // This function runs in a compromised context: see the top of the file.
384 // Runs on the crashing thread.
385 bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
386   if (filter_ && !filter_(callback_context_))
387     return false;
388
389   // Allow ourselves to be dumped if the signal is trusted.
390   bool signal_trusted = info->si_code > 0;
391   bool signal_pid_trusted = info->si_code == SI_USER ||
392       info->si_code == SI_TKILL;
393   if (signal_trusted || (signal_pid_trusted && info->si_pid == getpid())) {
394     sys_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
395   }
396   CrashContext context;
397   memcpy(&context.siginfo, info, sizeof(siginfo_t));
398   memcpy(&context.context, uc, sizeof(struct ucontext));
399 #if !defined(__ARM_EABI__) && !defined(__mips__)
400   // FP state is not part of user ABI on ARM Linux.
401   // In case of MIPS Linux FP state is already part of struct ucontext
402   // and 'float_state' is not a member of CrashContext.
403   struct ucontext *uc_ptr = (struct ucontext*)uc;
404   if (uc_ptr->uc_mcontext.fpregs) {
405     memcpy(&context.float_state,
406            uc_ptr->uc_mcontext.fpregs,
407            sizeof(context.float_state));
408   }
409 #endif
410   context.tid = syscall(__NR_gettid);
411   if (crash_handler_ != NULL) {
412     if (crash_handler_(&context, sizeof(context), callback_context_)) {
413       return true;
414     }
415   }
416   return GenerateDump(&context);
417 }
418
419 // This is a public interface to HandleSignal that allows the client to
420 // generate a crash dump. This function may run in a compromised context.
421 bool ExceptionHandler::SimulateSignalDelivery(int sig) {
422   siginfo_t siginfo = {};
423   // Mimic a trusted signal to allow tracing the process (see
424   // ExceptionHandler::HandleSignal().
425   siginfo.si_code = SI_USER;
426   siginfo.si_pid = getpid();
427   struct ucontext context;
428   getcontext(&context);
429   return HandleSignal(sig, &siginfo, &context);
430 }
431
432 // This function may run in a compromised context: see the top of the file.
433 bool ExceptionHandler::GenerateDump(CrashContext *context) {
434   if (IsOutOfProcess())
435     return crash_generation_client_->RequestDump(context, sizeof(*context));
436
437   static const unsigned kChildStackSize = 8000;
438   PageAllocator allocator;
439   uint8_t* stack = (uint8_t*) allocator.Alloc(kChildStackSize);
440   if (!stack)
441     return false;
442   // clone() needs the top-most address. (scrub just to be safe)
443   stack += kChildStackSize;
444   my_memset(stack - 16, 0, 16);
445
446   ThreadArgument thread_arg;
447   thread_arg.handler = this;
448   thread_arg.minidump_descriptor = &minidump_descriptor_;
449   thread_arg.pid = getpid();
450   thread_arg.context = context;
451   thread_arg.context_size = sizeof(*context);
452
453   // We need to explicitly enable ptrace of parent processes on some
454   // kernels, but we need to know the PID of the cloned process before we
455   // can do this. Create a pipe here which we can use to block the
456   // cloned process after creating it, until we have explicitly enabled ptrace
457   if(sys_pipe(fdes) == -1) {
458     // Creating the pipe failed. We'll log an error but carry on anyway,
459     // as we'll probably still get a useful crash report. All that will happen
460     // is the write() and read() calls will fail with EBADF
461     static const char no_pipe_msg[] = "ExceptionHandler::GenerateDump \
462                                        sys_pipe failed:";
463     logger::write(no_pipe_msg, sizeof(no_pipe_msg) - 1);
464     logger::write(strerror(errno), strlen(strerror(errno)));
465     logger::write("\n", 1);
466   }
467
468   const pid_t child = sys_clone(
469       ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
470       &thread_arg, NULL, NULL, NULL);
471
472   int r, status;
473   // Allow the child to ptrace us
474   sys_prctl(PR_SET_PTRACER, child, 0, 0, 0);
475   SendContinueSignalToChild();
476   do {
477     r = sys_waitpid(child, &status, __WALL);
478   } while (r == -1 && errno == EINTR);
479
480   sys_close(fdes[0]);
481   sys_close(fdes[1]);
482
483   if (r == -1) {
484     static const char msg[] = "ExceptionHandler::GenerateDump waitpid failed:";
485     logger::write(msg, sizeof(msg) - 1);
486     logger::write(strerror(errno), strlen(strerror(errno)));
487     logger::write("\n", 1);
488   }
489
490   bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
491   if (callback_)
492     success = callback_(minidump_descriptor_, callback_context_, success);
493   return success;
494 }
495
496 // This function runs in a compromised context: see the top of the file.
497 void ExceptionHandler::SendContinueSignalToChild() {
498   static const char okToContinueMessage = 'a';
499   int r;
500   r = HANDLE_EINTR(sys_write(fdes[1], &okToContinueMessage, sizeof(char)));
501   if(r == -1) {
502     static const char msg[] = "ExceptionHandler::SendContinueSignalToChild \
503                                sys_write failed:";
504     logger::write(msg, sizeof(msg) - 1);
505     logger::write(strerror(errno), strlen(strerror(errno)));
506     logger::write("\n", 1);
507   }
508 }
509
510 // This function runs in a compromised context: see the top of the file.
511 // Runs on the cloned process.
512 void ExceptionHandler::WaitForContinueSignal() {
513   int r;
514   char receivedMessage;
515   r = HANDLE_EINTR(sys_read(fdes[0], &receivedMessage, sizeof(char)));
516   if(r == -1) {
517     static const char msg[] = "ExceptionHandler::WaitForContinueSignal \
518                                sys_read failed:";
519     logger::write(msg, sizeof(msg) - 1);
520     logger::write(strerror(errno), strlen(strerror(errno)));
521     logger::write("\n", 1);
522   }
523 }
524
525 // This function runs in a compromised context: see the top of the file.
526 // Runs on the cloned process.
527 bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
528                               size_t context_size) {
529   if (minidump_descriptor_.IsFD()) {
530     return google_breakpad::WriteMinidump(minidump_descriptor_.fd(),
531                                           minidump_descriptor_.size_limit(),
532                                           crashing_process,
533                                           context,
534                                           context_size,
535                                           mapping_list_,
536                                           app_memory_list_);
537   }
538   return google_breakpad::WriteMinidump(minidump_descriptor_.path(),
539                                         minidump_descriptor_.size_limit(),
540                                         crashing_process,
541                                         context,
542                                         context_size,
543                                         mapping_list_,
544                                         app_memory_list_);
545 }
546
547 // static
548 bool ExceptionHandler::WriteMinidump(const string& dump_path,
549                                      MinidumpCallback callback,
550                                      void* callback_context) {
551   MinidumpDescriptor descriptor(dump_path);
552   ExceptionHandler eh(descriptor, NULL, callback, callback_context, false, -1);
553   return eh.WriteMinidump();
554 }
555
556 // In order to making using EBP to calculate the desired value for ESP
557 // a valid operation, ensure that this function is compiled with a
558 // frame pointer using the following attribute. This attribute
559 // is supported on GCC but not on clang.
560 #if defined(__i386__) && defined(__GNUC__) && !defined(__clang__)
561 __attribute__((optimize("no-omit-frame-pointer")))
562 #endif
563 bool ExceptionHandler::WriteMinidump() {
564   if (!IsOutOfProcess() && !minidump_descriptor_.IsFD()) {
565     // Update the path of the minidump so that this can be called multiple times
566     // and new files are created for each minidump.  This is done before the
567     // generation happens, as clients may want to access the MinidumpDescriptor
568     // after this call to find the exact path to the minidump file.
569     minidump_descriptor_.UpdatePath();
570   } else if (minidump_descriptor_.IsFD()) {
571     // Reposition the FD to its beginning and resize it to get rid of the
572     // previous minidump info.
573     lseek(minidump_descriptor_.fd(), 0, SEEK_SET);
574     static_cast<void>(ftruncate(minidump_descriptor_.fd(), 0));
575   }
576
577   // Allow this process to be dumped.
578   sys_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
579
580   CrashContext context;
581   int getcontext_result = getcontext(&context.context);
582   if (getcontext_result)
583     return false;
584
585 #if defined(__i386__)
586   // In CPUFillFromUContext in minidumpwriter.cc the stack pointer is retrieved
587   // from REG_UESP instead of from REG_ESP. REG_UESP is the user stack pointer
588   // and it only makes sense when running in kernel mode with a different stack
589   // pointer. When WriteMiniDump is called during normal processing REG_UESP is
590   // zero which leads to bad minidump files.
591   if (!context.context.uc_mcontext.gregs[REG_UESP]) {
592     // If REG_UESP is set to REG_ESP then that includes the stack space for the
593     // CrashContext object in this function, which is about 128 KB. Since the
594     // Linux dumper only records 32 KB of stack this would mean that nothing
595     // useful would be recorded. A better option is to set REG_UESP to REG_EBP,
596     // perhaps with a small negative offset in case there is any code that
597     // objects to them being equal.
598     context.context.uc_mcontext.gregs[REG_UESP] =
599       context.context.uc_mcontext.gregs[REG_EBP] - 16;
600     // The stack saving is based off of REG_ESP so it must be set to match the
601     // new REG_UESP.
602     context.context.uc_mcontext.gregs[REG_ESP] =
603       context.context.uc_mcontext.gregs[REG_UESP];
604   }
605 #endif
606
607 #if !defined(__ARM_EABI__) && !defined(__mips__)
608   // FPU state is not part of ARM EABI ucontext_t.
609   memcpy(&context.float_state, context.context.uc_mcontext.fpregs,
610          sizeof(context.float_state));
611 #endif
612   context.tid = sys_gettid();
613
614   // Add an exception stream to the minidump for better reporting.
615   memset(&context.siginfo, 0, sizeof(context.siginfo));
616   context.siginfo.si_signo = MD_EXCEPTION_CODE_LIN_DUMP_REQUESTED;
617 #if defined(__i386__)
618   context.siginfo.si_addr =
619       reinterpret_cast<void*>(context.context.uc_mcontext.gregs[REG_EIP]);
620 #elif defined(__x86_64__)
621   context.siginfo.si_addr =
622       reinterpret_cast<void*>(context.context.uc_mcontext.gregs[REG_RIP]);
623 #elif defined(__arm__)
624   context.siginfo.si_addr =
625       reinterpret_cast<void*>(context.context.uc_mcontext.arm_pc);
626 #elif defined(__mips__)
627   context.siginfo.si_addr =
628       reinterpret_cast<void*>(context.context.uc_mcontext.pc);
629 #else
630 #error "This code has not been ported to your platform yet."
631 #endif
632
633   return GenerateDump(&context);
634 }
635
636 void ExceptionHandler::AddMappingInfo(const string& name,
637                                       const uint8_t identifier[sizeof(MDGUID)],
638                                       uintptr_t start_address,
639                                       size_t mapping_size,
640                                       size_t file_offset) {
641   MappingInfo info;
642   info.start_addr = start_address;
643   info.size = mapping_size;
644   info.offset = file_offset;
645   strncpy(info.name, name.c_str(), sizeof(info.name) - 1);
646   info.name[sizeof(info.name) - 1] = '\0';
647
648   MappingEntry mapping;
649   mapping.first = info;
650   memcpy(mapping.second, identifier, sizeof(MDGUID));
651   mapping_list_.push_back(mapping);
652 }
653
654 void ExceptionHandler::RegisterAppMemory(void* ptr, size_t length) {
655   AppMemoryList::iterator iter =
656     std::find(app_memory_list_.begin(), app_memory_list_.end(), ptr);
657   if (iter != app_memory_list_.end()) {
658     // Don't allow registering the same pointer twice.
659     return;
660   }
661
662   AppMemory app_memory;
663   app_memory.ptr = ptr;
664   app_memory.length = length;
665   app_memory_list_.push_back(app_memory);
666 }
667
668 void ExceptionHandler::UnregisterAppMemory(void* ptr) {
669   AppMemoryList::iterator iter =
670     std::find(app_memory_list_.begin(), app_memory_list_.end(), ptr);
671   if (iter != app_memory_list_.end()) {
672     app_memory_list_.erase(iter);
673   }
674 }
675
676 // static
677 bool ExceptionHandler::WriteMinidumpForChild(pid_t child,
678                                              pid_t child_blamed_thread,
679                                              const string& dump_path,
680                                              MinidumpCallback callback,
681                                              void* callback_context) {
682   // This function is not run in a compromised context.
683   MinidumpDescriptor descriptor(dump_path);
684   descriptor.UpdatePath();
685   if (!google_breakpad::WriteMinidump(descriptor.path(),
686                                       child,
687                                       child_blamed_thread))
688       return false;
689
690   return callback ? callback(descriptor, callback_context, true) : true;
691 }
692
693 }  // namespace google_breakpad