Android NDK:获取回溯

ix0qys7i  于 2023-05-27  发布在  Android
关注(0)|答案(8)|浏览(297)

我正在开发通过NDK与Android一起工作的本地应用程序。我需要在发生崩溃时调用backtrace()函数。问题是NDK没有<execinfo.h>
有没有其他方法可以追踪到?

goucqfw6

goucqfw61#

Android没有backtrace(),但unwind.h在这里提供服务。可以通过dladdr()进行符号化。
下面的代码是我简单的回溯实现(没有demangling):

  1. #include <iostream>
  2. #include <iomanip>
  3. #include <unwind.h>
  4. #include <dlfcn.h>
  5. namespace {
  6. struct BacktraceState
  7. {
  8. void** current;
  9. void** end;
  10. };
  11. static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg)
  12. {
  13. BacktraceState* state = static_cast<BacktraceState*>(arg);
  14. uintptr_t pc = _Unwind_GetIP(context);
  15. if (pc) {
  16. if (state->current == state->end) {
  17. return _URC_END_OF_STACK;
  18. } else {
  19. *state->current++ = reinterpret_cast<void*>(pc);
  20. }
  21. }
  22. return _URC_NO_REASON;
  23. }
  24. }
  25. size_t captureBacktrace(void** buffer, size_t max)
  26. {
  27. BacktraceState state = {buffer, buffer + max};
  28. _Unwind_Backtrace(unwindCallback, &state);
  29. return state.current - buffer;
  30. }
  31. void dumpBacktrace(std::ostream& os, void** buffer, size_t count)
  32. {
  33. for (size_t idx = 0; idx < count; ++idx) {
  34. const void* addr = buffer[idx];
  35. const char* symbol = "";
  36. Dl_info info;
  37. if (dladdr(addr, &info) && info.dli_sname) {
  38. symbol = info.dli_sname;
  39. }
  40. os << " #" << std::setw(2) << idx << ": " << addr << " " << symbol << "\n";
  41. }
  42. }

它可以用于回溯到LogCat,如

  1. #include <sstream>
  2. #include <android/log.h>
  3. void backtraceToLogcat()
  4. {
  5. const size_t max = 30;
  6. void* buffer[max];
  7. std::ostringstream oss;
  8. dumpBacktrace(oss, buffer, captureBacktrace(buffer, max));
  9. __android_log_print(ANDROID_LOG_INFO, "app_name", "%s", oss.str().c_str());
  10. }
展开查看全部
nvbavucw

nvbavucw2#

下面是一些可以工作的完整代码,它从尤金Shapovalov的答案开始实现dump_stack(),并在设备上执行符号查找和C++名称解组。该解决方案:

  • 支持NDK r10 e(您不需要完整的Android AOSP源代码树)
  • 不需要任何额外的第三方库(没有libunwind、libbacktrace、corkscrew、CallStack)
  • 不依赖于设备上安装的任何共享库(例如在Android 5中被砍掉的开瓶器)
  • 不会强制您将地址Map到开发计算机上的符号;所有符号名称都显示在Android设备的代码中

它使用NDK中内置的以下设施:

  • NDK工具链/ dirs中的<unwind.h>标头(不是libunwind)
  • dladdr()
  • __cxxabiv1::__cxa_demangle()来自<cxxabi.h>(参见下面的STLport注解)

到目前为止,我只在一个基于arm的Android 5.1设备上测试了这个功能,并且我只从我的主程序调用它(而不是从信号处理程序)。我使用默认的ndk-build,它为arm平台选择gcc。
请评论,如果你能够使这项工作

  • 其他Android OS
  • 从一个SIGSEGV处理程序崩溃(我的目标只是打印一个堆栈跟踪Assert失败)
  • 使用clang工具集而不是gcc

请注意,r10 e NDK在gcc和clang工具集中都有针对许多架构的<unwind.h>代码,因此支持范围看起来很广。
C符号名称分离支持依赖于NDK附带的C STL中的__cxxabiv1::__cxa_demangle()函数。如果您使用GNU STL(Application.mk中的APP_STL := gnustl_staticgnustl_shared;更多信息请参见this page)。如果你目前根本没有使用STL,只需将APP_STL := gnustl_staticgnustl_shared添加到Application.mk。如果您使用STLport,您必须享受一种特殊的乐趣(更多信息见下文)。

**重要提示:**要使此代码工作,您不能使用-fvisibility=hidden gcc编译器选项(至少在调试版本中)。该选项通常用于在发布版本中隐藏符号。

很多人都注意到,ndk-build脚本会从NDK .so中剥离符号,同时将其复制到项目的libs/目录中。这是真的(在.so的两个副本上使用nm会产生非常不同的结果),然而,令人惊讶的是,这个特殊的剥离层并没有阻止下面的代码工作。不知何故,即使在剥离后,仍然有符号(只要你记得不要用-fvisibility=hidden编译)。显示为nm -D
关于这个主题的其他帖子讨论了其他编译器选项,如-funwind-tables。我没有发现我需要设置任何这样的选项。默认的ndk-build选项起作用。
要使用此代码,请将_my_log()替换为您喜欢的日志记录或字符串函数。
STLport用户请参见下面的特别说明。

  1. #include <unwind.h>
  2. #include <dlfcn.h>
  3. #include <cxxabi.h>
  4. struct android_backtrace_state
  5. {
  6. void **current;
  7. void **end;
  8. };
  9. _Unwind_Reason_Code android_unwind_callback(struct _Unwind_Context* context,
  10. void* arg)
  11. {
  12. android_backtrace_state* state = (android_backtrace_state *)arg;
  13. uintptr_t pc = _Unwind_GetIP(context);
  14. if (pc)
  15. {
  16. if (state->current == state->end)
  17. {
  18. return _URC_END_OF_STACK;
  19. }
  20. else
  21. {
  22. *state->current++ = reinterpret_cast<void*>(pc);
  23. }
  24. }
  25. return _URC_NO_REASON;
  26. }
  27. void dump_stack(void)
  28. {
  29. _my_log("android stack dump");
  30. const int max = 100;
  31. void* buffer[max];
  32. android_backtrace_state state;
  33. state.current = buffer;
  34. state.end = buffer + max;
  35. _Unwind_Backtrace(android_unwind_callback, &state);
  36. int count = (int)(state.current - buffer);
  37. for (int idx = 0; idx < count; idx++)
  38. {
  39. const void* addr = buffer[idx];
  40. const char* symbol = "";
  41. Dl_info info;
  42. if (dladdr(addr, &info) && info.dli_sname)
  43. {
  44. symbol = info.dli_sname;
  45. }
  46. int status = 0;
  47. char *demangled = __cxxabiv1::__cxa_demangle(symbol, 0, 0, &status);
  48. _my_log("%03d: 0x%p %s",
  49. idx,
  50. addr,
  51. (NULL != demangled && 0 == status) ?
  52. demangled : symbol);
  53. if (NULL != demangled)
  54. free(demangled);
  55. }
  56. _my_log("android stack dump done");
  57. }

如果您使用的是STLport STL而不是GNU STL,该怎么办?
你是我的,我也是你的。存在两个问题:

  • 第一个问题是STLport缺少来自<cxxabi.h>__cxxabiv1::__cxa_demangle()调用。您需要从this repository下载两个源文件cp-demangle.ccp-demangle.h,并将它们放在源文件下的demangle/子目录中,然后执行以下操作而不是#include <cxxabi.h>
  1. #define IN_LIBGCC2 1 // means we want to define __cxxabiv1::__cxa_demangle
  2. namespace __cxxabiv1
  3. {
  4. extern "C"
  5. {
  6. #include "demangle/cp-demangle.c"
  7. }
  8. }
  • 第二个问题更加棘手。事实证明,NDK中不是一个,也不是两个,而是三个不同的,不兼容的<unwind.h>类型。你猜对了,STLport中的<unwind.h>(实际上它在gabi库中,当你选择STLport时,它会出现)是不兼容的。事实上,STLport/gabi includes位于工具链includes之前(请参阅ndk-build输出的-I选项),这意味着STLport阻止您使用真实的的<unwind.h>。我找不到任何更好的解决方案,而不是进入并破解我安装的NDK中的文件名:
  • sources/cxx-stl/gabi++/include/unwind.hsources/cxx-stl/gabi++/include/unwind.h.NOT
  • sources/cxx-stl/gabi++/include/unwind-arm.hsources/cxx-stl/gabi++/include/unwind-arm.h.NOT
  • sources/cxx-stl/gabi++/include/unwind-itanium.hsources/cxx-stl/gabi++/include/unwind-itanium.h.NOT

我相信有一些更优雅的解决方案,但是我怀疑切换-I编译器选项的顺序可能会产生其他问题,因为STL通常希望覆盖工具链包含文件。
好好享受吧!

展开查看全部
33qvvth1

33qvvth13#

backtrace()是一个非标准的Glibc扩展,即使在ARM上也有些不稳定(我认为你需要用-funwind-tables构建所有东西,然后有一个新的Glibc?)
据我所知,Android使用的Bionic C库中并不包含这个函数。
您可以尝试将Glibc回溯的源代码拉到您的项目中,然后使用展开表重新构建有趣的内容,但这对我来说听起来很难。
如果你有调试信息,你可以尝试用一个附加到你的进程的脚本来启动GDB,并以这种方式打印一个回溯,但我不知道GDB是否能在Android上工作(尽管Android基本上是Linux,所以很多id很好,安装细节可能有问题?)你可以通过某种方式倾倒核心来获得更远的距离(仿生支持吗?),并在事后对其进行分析。

gt0wga4j

gt0wga4j4#

这里有一个疯狂的单行方法,可以获得非常详细的堆栈跟踪,包括C/C++(原生)和Java:滥用JNI

  1. env->FindClass(NULL);

只要您的应用程序是编译调试,或以其他方式使用Android的CheckJNI,这个错误的调用将触发Android的内置JNI检查器,这将产生一个华丽的堆栈跟踪控制台(从“艺术”日志源)。这个堆栈跟踪是在Android的libart.so内部完成的,使用了所有最新的技术和铃声,这些技术和铃声对于像我们这样的NDK用户来说并不容易获得。
您可以启用CheckJNI,即使是未编译调试的应用程序。请参阅此Google FAQ了解详情。
我不知道这个技巧是否适用于SIGSEGV处理程序(从SIGSEGV,您可能会得到错误堆栈的堆栈跟踪,或者可能根本不会触发Art),但值得一试。
如果您需要一个解决方案,使堆栈跟踪在您的代码中可用(例如所以你可以通过网络发送或记录它),看到我的另一个答案在这个相同的问题。

2hh7jdfx

2hh7jdfx5#

你可以使用CallStack:

  1. #include <utils/CallStack.h>
  2. void log_backtrace()
  3. {
  4. CallStack cs;
  5. cs.update(2);
  6. cs.dump();
  7. }

结果将需要通过c++filt或类似的方法进行de-mangling:

  1. D/CallStack( 2277): #08 0x0x40b09ac8: <_ZN7android15TimedEventQueue11threadEntryEv>+0x0x40b09961
  2. D/CallStack( 2277): #09 0x0x40b09b0c: <_ZN7android15TimedEventQueue13ThreadWrapperEPv>+0x0x40b09af9

you@work>$ c++ filt_ZN7android15TimedEventQueue11threadEntryEv_ZN7android15TimedEventQueue13ThreadWrapperEPv

  1. android::TimedEventQueue::threadEntry()
  2. android::TimedEventQueue::ThreadWrapper(void*)
展开查看全部
eagi6jfj

eagi6jfj6#

以下是如何使用libunwind在32位ARM上捕获回溯,该工具与现代Android NDK(如NDK r16b)捆绑在一起。

  1. // Android NDK r16b contains "libunwind.a" for armeabi-v7a ABI.
  2. // This library is even silently linked in by the ndk-build,
  3. // so we don't have to add it manually in "Android.mk".
  4. // We can use this library, but we need matching headers,
  5. // namely "libunwind.h" and "__libunwind_config.h".
  6. // For NDK r16b, the headers can be fetched here:
  7. // https://android.googlesource.com/platform/external/libunwind_llvm/+/ndk-r16/include/
  8. #include "libunwind.h"
  9. struct BacktraceState {
  10. const ucontext_t* signal_ucontext;
  11. size_t address_count = 0;
  12. static const size_t address_count_max = 30;
  13. uintptr_t addresses[address_count_max] = {};
  14. BacktraceState(const ucontext_t* ucontext) : signal_ucontext(ucontext) {}
  15. bool AddAddress(uintptr_t ip) {
  16. // No more space in the storage. Fail.
  17. if (address_count >= address_count_max)
  18. return false;
  19. // Add the address to the storage.
  20. addresses[address_count++] = ip;
  21. return true;
  22. }
  23. };
  24. void CaptureBacktraceUsingLibUnwind(BacktraceState* state) {
  25. assert(state);
  26. // Initialize unw_context and unw_cursor.
  27. unw_context_t unw_context = {};
  28. unw_getcontext(&unw_context);
  29. unw_cursor_t unw_cursor = {};
  30. unw_init_local(&unw_cursor, &unw_context);
  31. // Get more contexts.
  32. const ucontext_t* signal_ucontext = state->signal_ucontext;
  33. assert(signal_ucontext);
  34. const sigcontext* signal_mcontext = &(signal_ucontext->uc_mcontext);
  35. assert(signal_mcontext);
  36. // Set registers.
  37. unw_set_reg(&unw_cursor, UNW_ARM_R0, signal_mcontext->arm_r0);
  38. unw_set_reg(&unw_cursor, UNW_ARM_R1, signal_mcontext->arm_r1);
  39. unw_set_reg(&unw_cursor, UNW_ARM_R2, signal_mcontext->arm_r2);
  40. unw_set_reg(&unw_cursor, UNW_ARM_R3, signal_mcontext->arm_r3);
  41. unw_set_reg(&unw_cursor, UNW_ARM_R4, signal_mcontext->arm_r4);
  42. unw_set_reg(&unw_cursor, UNW_ARM_R5, signal_mcontext->arm_r5);
  43. unw_set_reg(&unw_cursor, UNW_ARM_R6, signal_mcontext->arm_r6);
  44. unw_set_reg(&unw_cursor, UNW_ARM_R7, signal_mcontext->arm_r7);
  45. unw_set_reg(&unw_cursor, UNW_ARM_R8, signal_mcontext->arm_r8);
  46. unw_set_reg(&unw_cursor, UNW_ARM_R9, signal_mcontext->arm_r9);
  47. unw_set_reg(&unw_cursor, UNW_ARM_R10, signal_mcontext->arm_r10);
  48. unw_set_reg(&unw_cursor, UNW_ARM_R11, signal_mcontext->arm_fp);
  49. unw_set_reg(&unw_cursor, UNW_ARM_R12, signal_mcontext->arm_ip);
  50. unw_set_reg(&unw_cursor, UNW_ARM_R13, signal_mcontext->arm_sp);
  51. unw_set_reg(&unw_cursor, UNW_ARM_R14, signal_mcontext->arm_lr);
  52. unw_set_reg(&unw_cursor, UNW_ARM_R15, signal_mcontext->arm_pc);
  53. unw_set_reg(&unw_cursor, UNW_REG_IP, signal_mcontext->arm_pc);
  54. unw_set_reg(&unw_cursor, UNW_REG_SP, signal_mcontext->arm_sp);
  55. // unw_step() does not return the first IP,
  56. // the address of the instruction which caused the crash.
  57. // Thus let's add this address manually.
  58. state->AddAddress(signal_mcontext->arm_pc);
  59. // Unwind frames one by one, going up the frame stack.
  60. while (unw_step(&unw_cursor) > 0) {
  61. unw_word_t ip = 0;
  62. unw_get_reg(&unw_cursor, UNW_REG_IP, &ip);
  63. bool ok = state->AddAddress(ip);
  64. if (!ok)
  65. break;
  66. }
  67. }
  68. void SigActionHandler(int sig, siginfo_t* info, void* ucontext) {
  69. const ucontext_t* signal_ucontext = (const ucontext_t*)ucontext;
  70. assert(signal_ucontext);
  71. BacktraceState backtrace_state(signal_ucontext);
  72. CaptureBacktraceUsingLibUnwind(&backtrace_state);
  73. exit(0);
  74. }

下面是一个示例回溯测试应用程序,其中包含3个实现的回溯方法,包括上面显示的方法。
https://github.com/alexeikh/android-ndk-backtrace-test

展开查看全部
wr98u20j

wr98u20j7#

如果你只想要几个(例如2 - 5个)最上面的调用帧,如果你的GCC足够新,你可以考虑使用一些返回地址或帧地址内置。
(But我不太了解Android,所以我可能错了。

owfi6suc

owfi6suc8#

Bionic execinfo.h标头自API级别33(Android 14)起已公开,允许您在运行时收集回溯,就像在常规Linux上一样。backtrace的手册页上提供了一个示例:https://man7.org/linux/man-pages/man3/backtrace.3.html
对于旧版本的Android,您可以在以下位置重用代码:https://cs.android.com/android/platform/superproject/+/master:bionic/libc/bionic/execinfo.cpp

相关问题