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