stacktrace_libunwind-inl.h 1.54 KB
Newer Older
's avatar
committed
1 2 3 4 5 6 7
// Copyright 2005 - 2007 Google Inc.
// All rights reserved.
//
// Author: Arun Sharma
//
// Produce stack trace using libunwind

8 9
#include "utilities.h"

's avatar
committed
10
extern "C" {
11
#define UNW_LOCAL_ONLY
's avatar
committed
12 13
#include <libunwind.h>
}
14 15
#include "glog/raw_logging.h"
#include "stacktrace.h"
's avatar
committed
16 17 18 19

_START_GOOGLE_NAMESPACE_

// Sometimes, we can try to get a stack trace from within a stack
20 21 22 23
// trace, because libunwind can call mmap (maybe indirectly via an
// internal mmap based memory allocator), and that mmap gets trapped
// and causes a stack-trace request.  If were to try to honor that
// recursive request, we'd end up with infinite recursion or deadlock.
's avatar
committed
24 25
// Luckily, it's safe to ignore those subsequent traces.  In such
// cases, we return 0 to indicate the situation.
26
static bool g_now_entering = false;
's avatar
committed
27 28 29 30 31 32 33 34

// If you change this function, also change GetStackFrames below.
int GetStackTrace(void** result, int max_depth, int skip_count) {
  void *ip;
  int n = 0;
  unw_cursor_t cursor;
  unw_context_t uc;

35
  if (sync_val_compare_and_swap(&g_now_entering, false, true)) {
's avatar
committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    return 0;
  }

  unw_getcontext(&uc);
  RAW_CHECK(unw_init_local(&cursor, &uc) >= 0, "unw_init_local failed");
  skip_count++;         // Do not include the "GetStackTrace" frame

  while (n < max_depth) {
    int ret = unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *) &ip);
    if (ret < 0)
      break;
    if (skip_count > 0) {
      skip_count--;
    } else {
      result[n++] = ip;
    }
    ret = unw_step(&cursor);
    if (ret <= 0)
      break;
  }

57
  g_now_entering = false;
's avatar
committed
58 59 60 61
  return n;
}

_END_GOOGLE_NAMESPACE_