backtrace.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Perform stack unwinding by using the _Unwind_Backtrace.
  3. *
  4. * User application that wants to use backtrace needs to be
  5. * compiled with -fasynchronous-unwid-tables option and -rdynamic i
  6. * to get full symbols printed.
  7. *
  8. * Author(s): Khem Raj <raj.khem@gmail.com>
  9. * - ARM specific implementation of backtrace
  10. *
  11. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  12. *
  13. */
  14. #include <libgcc_s.h>
  15. #include <execinfo.h>
  16. #include <dlfcn.h>
  17. #include <stdlib.h>
  18. #include <unwind.h>
  19. #include <assert.h>
  20. #include <stdio.h>
  21. struct trace_arg
  22. {
  23. void **array;
  24. int cnt, size;
  25. };
  26. static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
  27. static _Unwind_VRS_Result (*unwind_vrs_get) (_Unwind_Context *,
  28. _Unwind_VRS_RegClass,
  29. _uw,
  30. _Unwind_VRS_DataRepresentation,
  31. void *);
  32. static void backtrace_init (void)
  33. {
  34. void *handle = dlopen (LIBGCC_S_SO, RTLD_LAZY);
  35. if (handle == NULL
  36. || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL)
  37. || ((unwind_vrs_get = dlsym (handle, "_Unwind_VRS_Get")) == NULL)) {
  38. printf(LIBGCC_S_SO " must be installed for backtrace to work\n");
  39. abort();
  40. }
  41. }
  42. /* This function is identical to "_Unwind_GetGR", except that it uses
  43. "unwind_vrs_get" instead of "_Unwind_VRS_Get". */
  44. static inline _Unwind_Word
  45. unwind_getgr (_Unwind_Context *context, int regno)
  46. {
  47. _uw val;
  48. unwind_vrs_get (context, _UVRSC_CORE, regno, _UVRSD_UINT32, &val);
  49. return val;
  50. }
  51. /* This macro is identical to the _Unwind_GetIP macro, except that it
  52. uses "unwind_getgr" instead of "_Unwind_GetGR". */
  53. #define unwind_getip(context) \
  54. (unwind_getgr (context, 15) & ~(_Unwind_Word)1)
  55. static _Unwind_Reason_Code
  56. backtrace_helper (struct _Unwind_Context *ctx, void *a)
  57. {
  58. struct trace_arg *arg = a;
  59. assert (unwind_getip(ctx) != NULL);
  60. /* We are first called with address in the __backtrace function. Skip it. */
  61. if (arg->cnt != -1)
  62. arg->array[arg->cnt] = (void *) unwind_getip (ctx);
  63. if (++arg->cnt == arg->size)
  64. return _URC_END_OF_STACK;
  65. return _URC_NO_REASON;
  66. }
  67. /*
  68. * Perform stack unwinding by using the _Unwind_Backtrace.
  69. *
  70. */
  71. int backtrace (void **array, int size)
  72. {
  73. struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
  74. if (unwind_backtrace == NULL)
  75. backtrace_init();
  76. if (size >= 1)
  77. unwind_backtrace (backtrace_helper, &arg);
  78. return arg.cnt != -1 ? arg.cnt : 0;
  79. }