Created
April 22, 2021 10:45
-
-
Save xiaozhuai/2e95c58147d00cfb012a4fcacbc31c50 to your computer and use it in GitHub Desktop.
Android native c++ get back trace (stacktrace)
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
#include <tinyformat.h> | |
#include <unwind.h> | |
#include <cxxabi.h> | |
#include <dlfcn.h> | |
struct android_backtrace_state { | |
void **current; | |
void **end; | |
}; | |
_Unwind_Reason_Code android_unwind_callback(struct _Unwind_Context *context, void *arg) { | |
auto *state = (android_backtrace_state *) 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; | |
} | |
std::string getBacktrace(int skip, int max) { | |
std::stringstream ss; | |
void *buffer[max]; | |
android_backtrace_state state{}; | |
state.current = buffer; | |
state.end = buffer + max; | |
_Unwind_Backtrace(android_unwind_callback, &state); | |
int count = (int) (state.current - buffer); | |
for (int idx = skip; 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; | |
} | |
int status = 0; | |
char *demangled = abi::__cxa_demangle(symbol, nullptr, nullptr, &status); | |
ss << tfm::format("\n #%02d: %lx %s", idx - skip, addr, status == 0 ? demangled : symbol); | |
if (nullptr != demangled) free(demangled); | |
} | |
return ss.str(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment