backtrace.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 <execinfo.h>
  15. #include <dlfcn.h>
  16. #include <stdlib.h>
  17. #include <unwind.h>
  18. #include <assert.h>
  19. #include <stdio.h>
  20. struct trace_arg
  21. {
  22. void **array;
  23. int cnt, size;
  24. };
  25. static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
  26. static _Unwind_VRS_Result (*unwind_vrs_get) (_Unwind_Context *,
  27. _Unwind_VRS_RegClass,
  28. _uw,
  29. _Unwind_VRS_DataRepresentation,
  30. void *);
  31. static void backtrace_init (void)
  32. {
  33. void *handle = dlopen ("libgcc_s.so.1", RTLD_LAZY);
  34. if (handle == NULL
  35. || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL)
  36. || ((unwind_vrs_get = dlsym (handle, "_Unwind_VRS_Get")) == NULL)) {
  37. printf("libgcc_s.so.1 must be installed for backtrace to work\n");
  38. abort();
  39. }
  40. }
  41. /* This function is identical to "_Unwind_GetGR", except that it uses
  42. "unwind_vrs_get" instead of "_Unwind_VRS_Get". */
  43. static inline _Unwind_Word
  44. unwind_getgr (_Unwind_Context *context, int regno)
  45. {
  46. _uw val;
  47. unwind_vrs_get (context, _UVRSC_CORE, regno, _UVRSD_UINT32, &val);
  48. return val;
  49. }
  50. /* This macro is identical to the _Unwind_GetIP macro, except that it
  51. uses "unwind_getgr" instead of "_Unwind_GetGR". */
  52. #define unwind_getip(context) \
  53. (unwind_getgr (context, 15) & ~(_Unwind_Word)1)
  54. static _Unwind_Reason_Code
  55. backtrace_helper (struct _Unwind_Context *ctx, void *a)
  56. {
  57. struct trace_arg *arg = a;
  58. assert (unwind_getip(ctx) != NULL);
  59. /* We are first called with address in the __backtrace function. Skip it. */
  60. if (arg->cnt != -1)
  61. arg->array[arg->cnt] = (void *) unwind_getip (ctx);
  62. if (++arg->cnt == arg->size)
  63. return _URC_END_OF_STACK;
  64. return _URC_NO_REASON;
  65. }
  66. /*
  67. * Perform stack unwinding by using the _Unwind_Backtrace.
  68. *
  69. */
  70. int backtrace (void **array, int size)
  71. {
  72. struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
  73. if (unwind_backtrace == NULL)
  74. backtrace_init();
  75. if (size >= 1)
  76. unwind_backtrace (backtrace_helper, &arg);
  77. return arg.cnt != -1 ? arg.cnt : 0;
  78. }