Created
September 13, 2016 10:29
-
-
Save wangmuy/7d72b8a67cb414fb312a46e9b591be34 to your computer and use it in GitHub Desktop.
android native stack backtrace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef BACKTRACE_UTILS_h | |
#define BACKTRACE_UTILS_h | |
// ref: http://stackoverflow.com/questions/8115192/android-ndk-getting-the-backtrace | |
#include <cstdio> | |
#include <ostream> | |
#include <sstream> | |
size_t captureBacktrace(void** buffer, size_t max); | |
void dumpBacktrace(std::ostream& os, void** buffer, size_t count); | |
/** usage: | |
std::ostringstream oss; | |
getBacktrace(oss, 30); | |
__android_log_print(ANDROID_LOG_INFO, "app_name", "%s", oss.str().c_str()); | |
*/ | |
void getBacktrace(std::ostringstream& os, const size_t max=30); | |
#endif | |
#include <iomanip> | |
#include <unwind.h> | |
#include <dlfcn.h> | |
#include "BacktraceUtils.h" | |
struct BacktraceState { | |
void** current; | |
void** end; | |
}; | |
static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg) | |
{ | |
BacktraceState* state = static_cast<BacktraceState*>(arg); | |
uintptr_t pc = _Unwind_GetIP(context); | |
if(pc) { | |
if(state->current == state->end) { | |
return _URC_END_OF_STACK; | |
} else { | |
*state->current++ = reinterpret_cast<void*>(pc); | |
} | |
} | |
return _URC_NO_REASON; | |
} | |
size_t captureBacktrace(void** buffer, size_t max) | |
{ | |
BacktraceState state = {buffer, buffer+max}; | |
_Unwind_Backtrace(unwindCallback, &state); | |
return state.current - buffer; | |
} | |
void dumpBacktrace(std::ostream& os, void** buffer, size_t count) | |
{ | |
for(size_t idx=0; idx < count; ++idx) { | |
const void* addr = buffer[idx]; | |
const char* symbol = ""; | |
Dl_info info; | |
if(dladdr(addr, &info) && info.dli_sname) { | |
symbol = info.dli_sname; | |
} | |
os << " #" << std::setw(2) << idx << ": " << addr << " " << symbol << "\n"; | |
} | |
} | |
void getBacktrace(std::ostringstream& oss, const size_t max) | |
{ | |
void* buffer[max]; | |
dumpBacktrace(oss, buffer, captureBacktrace(buffer, max)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment