PageRenderTime 66ms CodeModel.GetById 2ms app.highlight 59ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/client/linux/handler/exception_handler.cc

http://github.com/tomahawk-player/tomahawk
C++ | 523 lines | 328 code | 65 blank | 130 comment | 58 complexity | 6b51de1e88bd892a94d2cf4e2b085c8a MD5 | raw file
  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#if !defined(__ANDROID__)
 81#include <sys/signal.h>
 82#include <sys/ucontext.h>
 83#include <sys/user.h>
 84#include <ucontext.h>
 85#endif
 86
 87#include <algorithm>
 88#include <utility>
 89#include <vector>
 90
 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/guid_creator.h"
 97#include "common/linux/eintr_wrapper.h"
 98#include "third_party/lss/linux_syscall_support.h"
 99
100#include "linux/sched.h"
101
102#ifndef PR_SET_PTRACER
103#define PR_SET_PTRACER 0x59616d61
104#endif
105
106// A wrapper for the tgkill syscall: send a signal to a specific thread.
107static int tgkill(pid_t tgid, pid_t tid, int sig) {
108  return syscall(__NR_tgkill, tgid, tid, sig);
109  return 0;
110}
111
112namespace google_breakpad {
113
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.
117static const int kExceptionSignals[] = {
118  SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
119};
120
121// We can stack multiple exception handlers. In that case, this is the global
122// which holds the stack.
123std::vector<ExceptionHandler*>* ExceptionHandler::handler_stack_ = NULL;
124unsigned ExceptionHandler::handler_stack_index_ = 0;
125pthread_mutex_t ExceptionHandler::handler_stack_mutex_ =
126    PTHREAD_MUTEX_INITIALIZER;
127
128// Runs before crashing: normal context.
129ExceptionHandler::ExceptionHandler(const std::string &dump_path,
130                                   FilterCallback filter,
131                                   MinidumpCallback callback,
132                                   void *callback_context,
133                                   bool install_handler)
134  : filter_(filter),
135    callback_(callback),
136    callback_context_(callback_context),
137    handler_installed_(install_handler)
138{
139  Init(dump_path, -1);
140}
141
142ExceptionHandler::ExceptionHandler(const std::string &dump_path,
143                                   FilterCallback filter,
144                                   MinidumpCallback callback,
145                                   void* callback_context,
146                                   bool install_handler,
147                                   const int server_fd)
148  : filter_(filter),
149    callback_(callback),
150    callback_context_(callback_context),
151    handler_installed_(install_handler)
152{
153  Init(dump_path, server_fd);
154}
155
156// Runs before crashing: normal context.
157ExceptionHandler::~ExceptionHandler() {
158  UninstallHandlers();
159}
160
161void ExceptionHandler::Init(const std::string &dump_path,
162                            const int server_fd)
163{
164  crash_handler_ = NULL;
165  if (0 <= server_fd)
166    crash_generation_client_
167      .reset(CrashGenerationClient::TryCreate(server_fd));
168
169  if (handler_installed_)
170    InstallHandlers();
171
172  if (!IsOutOfProcess())
173    set_dump_path(dump_path);
174
175  pthread_mutex_lock(&handler_stack_mutex_);
176  if (handler_stack_ == NULL)
177    handler_stack_ = new std::vector<ExceptionHandler *>;
178  handler_stack_->push_back(this);
179  pthread_mutex_unlock(&handler_stack_mutex_);
180}
181
182// Runs before crashing: normal context.
183bool ExceptionHandler::InstallHandlers() {
184  // We run the signal handlers on an alternative stack because we might have
185  // crashed because of a stack overflow.
186
187  // We use this value rather than SIGSTKSZ because we would end up overrunning
188  // such a small stack.
189  static const unsigned kSigStackSize = 8192;
190
191  stack_t stack;
192  // Only set an alternative stack if there isn't already one, or if the current
193  // one is too small.
194  if (sys_sigaltstack(NULL, &stack) == -1 || !stack.ss_sp ||
195      stack.ss_size < kSigStackSize) {
196    memset(&stack, 0, sizeof(stack));
197    stack.ss_sp = malloc(kSigStackSize);
198    stack.ss_size = kSigStackSize;
199
200    if (sys_sigaltstack(&stack, NULL) == -1)
201      return false;
202  }
203
204  struct sigaction sa;
205  memset(&sa, 0, sizeof(sa));
206  sigemptyset(&sa.sa_mask);
207
208  // mask all exception signals when we're handling one of them.
209  for (unsigned i = 0; kExceptionSignals[i] != -1; ++i)
210    sigaddset(&sa.sa_mask, kExceptionSignals[i]);
211
212  sa.sa_sigaction = SignalHandler;
213  sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
214
215  for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) {
216    struct sigaction* old = new struct sigaction;
217    if (sigaction(kExceptionSignals[i], &sa, old) == -1)
218      return false;
219    old_handlers_.push_back(std::make_pair(kExceptionSignals[i], old));
220  }
221  return true;
222}
223
224// Runs before crashing: normal context.
225void ExceptionHandler::UninstallHandlers() {
226  for (unsigned i = 0; i < old_handlers_.size(); ++i) {
227    struct sigaction *action =
228        reinterpret_cast<struct sigaction*>(old_handlers_[i].second);
229    sigaction(old_handlers_[i].first, action, NULL);
230    delete action;
231  }
232  pthread_mutex_lock(&handler_stack_mutex_);
233  std::vector<ExceptionHandler*>::iterator handler =
234      std::find(handler_stack_->begin(), handler_stack_->end(), this);
235  handler_stack_->erase(handler);
236  pthread_mutex_unlock(&handler_stack_mutex_);
237  old_handlers_.clear();
238}
239
240// Runs before crashing: normal context.
241void ExceptionHandler::UpdateNextID() {
242  GUID guid;
243  char guid_str[kGUIDStringLength + 1];
244  if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) {
245    next_minidump_id_ = guid_str;
246    next_minidump_id_c_ = next_minidump_id_.c_str();
247
248    char minidump_path[PATH_MAX];
249    snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp",
250             dump_path_c_,
251             guid_str);
252
253    next_minidump_path_ = minidump_path;
254    next_minidump_path_c_ = next_minidump_path_.c_str();
255  }
256}
257
258// void ExceptionHandler::set_crash_handler(HandlerCallback callback) {
259//   crash_handler_ = callback;
260// }
261
262// This function runs in a compromised context: see the top of the file.
263// Runs on the crashing thread.
264// static
265void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
266  // All the exception signals are blocked at this point.
267  pthread_mutex_lock(&handler_stack_mutex_);
268
269  if (!handler_stack_->size()) {
270    pthread_mutex_unlock(&handler_stack_mutex_);
271    return;
272  }
273
274  for (int i = handler_stack_->size() - 1; i >= 0; --i) {
275    if ((*handler_stack_)[i]->HandleSignal(sig, info, uc)) {
276      // successfully handled: We are in an invalid state since an exception
277      // signal has been delivered. We don't call the exit handlers because
278      // they could end up corrupting on-disk state.
279      break;
280    }
281  }
282
283  pthread_mutex_unlock(&handler_stack_mutex_);
284
285  if (info->si_pid) {
286    // This signal was triggered by somebody sending us the signal with kill().
287    // In order to retrigger it, we have to queue a new signal by calling
288    // kill() ourselves.
289    if (tgkill(getpid(), syscall(__NR_gettid), sig) < 0) {
290      // If we failed to kill ourselves (e.g. because a sandbox disallows us
291      // to do so), we instead resort to terminating our process. This will
292      // result in an incorrect exit code.
293      _exit(1);
294    }
295  } else {
296    // This was a synchronous signal triggered by a hard fault (e.g. SIGSEGV).
297    // No need to reissue the signal. It will automatically trigger again,
298    // when we return from the signal handler.
299  }
300
301  // As soon as we return from the signal handler, our signal will become
302  // unmasked. At that time, we will  get terminated with the same signal that
303  // was triggered originally. This allows our parent to know that we crashed.
304  // The default action for all the signals which we catch is Core, so
305  // this is the end of us.
306  signal(sig, SIG_DFL);
307}
308
309struct ThreadArgument {
310  pid_t pid;  // the crashing process
311  ExceptionHandler* handler;
312  const void* context;  // a CrashContext structure
313  size_t context_size;
314};
315
316// This is the entry function for the cloned process. We are in a compromised
317// context here: see the top of the file.
318// static
319int ExceptionHandler::ThreadEntry(void *arg) {
320  const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
321
322  // Block here until the crashing process unblocks us when
323  // we're allowed to use ptrace
324  thread_arg->handler->WaitForContinueSignal();
325
326  return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
327                                     thread_arg->context_size) == false;
328}
329
330// This function runs in a compromised context: see the top of the file.
331// Runs on the crashing thread.
332bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
333  if (filter_ && !filter_(callback_context_))
334    return false;
335
336  // Allow ourselves to be dumped if the signal is trusted.
337  bool signal_trusted = info->si_code > 0;
338  bool signal_pid_trusted = info->si_code == SI_USER ||
339      info->si_code == SI_TKILL;
340  if (signal_trusted || (signal_pid_trusted && info->si_pid == getpid())) {
341    sys_prctl(PR_SET_DUMPABLE, 1);
342  }
343  CrashContext context;
344  memcpy(&context.siginfo, info, sizeof(siginfo_t));
345  memcpy(&context.context, uc, sizeof(struct ucontext));
346#if !defined(__ARM_EABI__)
347  // FP state is not part of user ABI on ARM Linux.
348  struct ucontext *uc_ptr = (struct ucontext*)uc;
349  if (uc_ptr->uc_mcontext.fpregs) {
350    memcpy(&context.float_state,
351           uc_ptr->uc_mcontext.fpregs,
352           sizeof(context.float_state));
353  }
354#endif
355  context.tid = syscall(__NR_gettid);
356  if (crash_handler_ != NULL) {
357    if (crash_handler_(&context, sizeof(context),
358                       callback_context_)) {
359      return true;
360    }
361  }
362  return GenerateDump(&context);
363}
364
365// This function may run in a compromised context: see the top of the file.
366bool ExceptionHandler::GenerateDump(CrashContext *context) {
367  if (IsOutOfProcess())
368    return crash_generation_client_->RequestDump(context, sizeof(*context));
369
370  static const unsigned kChildStackSize = 8000;
371  PageAllocator allocator;
372  uint8_t* stack = (uint8_t*) allocator.Alloc(kChildStackSize);
373  if (!stack)
374    return false;
375  // clone() needs the top-most address. (scrub just to be safe)
376  stack += kChildStackSize;
377  my_memset(stack - 16, 0, 16);
378
379  ThreadArgument thread_arg;
380  thread_arg.handler = this;
381  thread_arg.pid = getpid();
382  thread_arg.context = context;
383  thread_arg.context_size = sizeof(*context);
384
385  // We need to explicitly enable ptrace of parent processes on some
386  // kernels, but we need to know the PID of the cloned process before we
387  // can do this. Create a pipe here which we can use to block the
388  // cloned process after creating it, until we have explicitly enabled ptrace
389  if(sys_pipe(fdes) == -1) {
390    // Creating the pipe failed. We'll log an error but carry on anyway,
391    // as we'll probably still get a useful crash report. All that will happen
392    // is the write() and read() calls will fail with EBADF
393    static const char no_pipe_msg[] = "ExceptionHandler::GenerateDump \
394                                       sys_pipe failed:";
395    logger::write(no_pipe_msg, sizeof(no_pipe_msg) - 1);
396    logger::write(strerror(errno), strlen(strerror(errno)));
397    logger::write("\n", 1);
398  }
399
400#if defined(__ANDROID__)
401  const pid_t child = clone(
402      ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
403      &thread_arg);
404#else
405  const pid_t child = sys_clone(
406      ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
407      &thread_arg, NULL, NULL, NULL);
408#endif
409  int r, status;
410  // Allow the child to ptrace us
411  sys_prctl(PR_SET_PTRACER, child);
412  SendContinueSignalToChild();
413  do {
414    r = sys_waitpid(child, &status, __WALL);
415  } while (r == -1 && errno == EINTR);
416
417  sys_close(fdes[0]);
418  sys_close(fdes[1]);
419
420  if (r == -1) {
421    static const char msg[] = "ExceptionHandler::GenerateDump waitpid failed:";
422    logger::write(msg, sizeof(msg) - 1);
423    logger::write(strerror(errno), strlen(strerror(errno)));
424    logger::write("\n", 1);
425  }
426
427  bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
428
429  if (callback_)
430    success = callback_(dump_path_c_, next_minidump_id_c_,
431                        callback_context_, success);
432
433  return success;
434}
435
436// This function runs in a compromised context: see the top of the file.
437void ExceptionHandler::SendContinueSignalToChild() {
438  static const char okToContinueMessage = 'a';
439  int r;
440  r = HANDLE_EINTR(sys_write(fdes[1], &okToContinueMessage, sizeof(char)));
441  if(r == -1) {
442    static const char msg[] = "ExceptionHandler::SendContinueSignalToChild \
443                               sys_write failed:";
444    logger::write(msg, sizeof(msg) - 1);
445    logger::write(strerror(errno), strlen(strerror(errno)));
446    logger::write("\n", 1);
447  }
448}
449
450// This function runs in a compromised context: see the top of the file.
451// Runs on the cloned process.
452void ExceptionHandler::WaitForContinueSignal() {
453  int r;
454  char receivedMessage;
455  r = HANDLE_EINTR(sys_read(fdes[0], &receivedMessage, sizeof(char)));
456  if(r == -1) {
457    static const char msg[] = "ExceptionHandler::WaitForContinueSignal \
458                               sys_read failed:";
459    logger::write(msg, sizeof(msg) - 1);
460    logger::write(strerror(errno), strlen(strerror(errno)));
461    logger::write("\n", 1);
462  }
463}
464
465// This function runs in a compromised context: see the top of the file.
466// Runs on the cloned process.
467bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
468                              size_t context_size) {
469  return google_breakpad::WriteMinidump(next_minidump_path_c_,
470                                        crashing_process,
471                                        context,
472                                        context_size,
473                                        mapping_list_);
474}
475
476// static
477bool ExceptionHandler::WriteMinidump(const std::string &dump_path,
478                                     MinidumpCallback callback,
479                                     void* callback_context) {
480  ExceptionHandler eh(dump_path, NULL, callback, callback_context, false);
481  return eh.WriteMinidump();
482}
483
484bool ExceptionHandler::WriteMinidump() {
485#if !defined(__ARM_EABI__)
486  // Allow ourselves to be dumped.
487  sys_prctl(PR_SET_DUMPABLE, 1);
488
489  CrashContext context;
490  int getcontext_result = getcontext(&context.context);
491  if (getcontext_result)
492    return false;
493  memcpy(&context.float_state, context.context.uc_mcontext.fpregs,
494         sizeof(context.float_state));
495  context.tid = sys_gettid();
496
497  bool success = GenerateDump(&context);
498  UpdateNextID();
499  return success;
500#else
501  return false;
502#endif  // !defined(__ARM_EABI__)
503}
504
505void ExceptionHandler::AddMappingInfo(const std::string& name,
506                                      const u_int8_t identifier[sizeof(MDGUID)],
507                                      uintptr_t start_address,
508                                      size_t mapping_size,
509                                      size_t file_offset) {
510  MappingInfo info;
511  info.start_addr = start_address;
512  info.size = mapping_size;
513  info.offset = file_offset;
514  strncpy(info.name, name.c_str(), sizeof(info.name) - 1);
515  info.name[sizeof(info.name) - 1] = '\0';
516
517  MappingEntry mapping;
518  mapping.first = info;
519  memcpy(mapping.second, identifier, sizeof(MDGUID));
520  mapping_list_.push_back(mapping);
521}
522
523}  // namespace google_breakpad