stack_trace.cc 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#include "util/stack_trace.h"

#ifdef OS_LINUX

#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

12
namespace rocksdb {
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

static const char* GetExecutableName()
{
  static char name[1024];

  char link[1024];
  snprintf(link, sizeof(link), "/proc/%d/exe", getpid());
  auto read = readlink(link, name, sizeof(name));
  if (-1 == read) {
    return nullptr;
  } else {
    name[read] = 0;
    return name;
  }
}

static void StackTraceHandler(int sig) {
  // reset to default handler
  signal(sig, SIG_DFL);

33
  fprintf(stderr, "Received signal %d (%s)\n", sig, strsignal(sig));
34 35 36 37 38 39 40 41 42 43 44 45 46

  const int kMaxFrames = 100;
  void *frames[kMaxFrames];

  auto num_frames = backtrace(frames, kMaxFrames);
  auto symbols = backtrace_symbols(frames, num_frames);

  auto executable = GetExecutableName();

  const int kSkip = 2; // skip the top two signal handler related frames

  for (int i = kSkip; i < num_frames; ++i)
  {
47
    fprintf(stderr, "#%-2d %p ", i - kSkip, frames[i]);
48
    if (symbols) {
49
      fprintf(stderr, "%s ", symbols[i]);
50 51 52 53 54 55 56 57 58 59
    }
    if (executable) {
      // out source to addr2line, for the address translation
      const int kLineMax = 256;
      char cmd[kLineMax];
      sprintf(cmd,"addr2line %p -e %s 2>&1", frames[i] , executable);
      auto f = popen(cmd, "r");
      if (f) {
        char line[kLineMax];
        while (fgets(line, sizeof(line), f)) {
60
          fprintf(stderr, "%s", line);
61 62 63
        }
        pclose(f);
      } else {
64
        fprintf(stderr, "\n");
65 66
      }
    } else {
67
      fprintf(stderr, "\n");
68 69 70 71 72 73 74 75 76 77 78 79 80 81
    }
  }

  // re-signal to default handler (so we still get core dump if needed...)
  raise(sig);
}

void InstallStackTraceHandler() {
  // just use the plain old signal as it's simple and sufficient
  // for this use case
  signal(SIGILL, StackTraceHandler);
  signal(SIGSEGV, StackTraceHandler);
  signal(SIGBUS, StackTraceHandler);
  signal(SIGABRT, StackTraceHandler);
82 83 84

  printf("Installed stack trace handler for SIGILL SIGSEGV SIGBUS SIGABRT\n");

85 86
}

87
}   // namespace rocksdb
88 89 90

#else // no-op for non-linux system for now

91
namespace rocksdb {
92 93 94 95 96 97

void InstallStackTraceHandler() {}

}

#endif // OS_LINUX