backtrace.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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-unwind-tables option and -rdynamic to get full
  6. * symbols printed.
  7. *
  8. * Copyright (C) 2009, 2010 STMicroelectronics Ltd.
  9. *
  10. * Author(s): Giuseppe Cavallaro <peppe.cavallaro@st.com>
  11. * - Initial implementation for glibc
  12. *
  13. * Author(s): Carmelo Amoroso <carmelo.amoroso@st.com>
  14. * - Reworked for uClibc
  15. * - use dlsym/dlopen from libdl
  16. * - rewrite initialisation to not use libc_once
  17. * - make it available in static link too
  18. *
  19. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  20. *
  21. */
  22. #include <libgcc_s.h>
  23. #include <execinfo.h>
  24. #include <dlfcn.h>
  25. #include <stdlib.h>
  26. #include <unwind.h>
  27. #include <assert.h>
  28. #include <stdio.h>
  29. struct trace_arg
  30. {
  31. void **array;
  32. int cnt, size;
  33. };
  34. #ifdef SHARED
  35. static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
  36. static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *);
  37. static void backtrace_init (void)
  38. {
  39. void *handle = dlopen (LIBGCC_S_SO, RTLD_LAZY);
  40. if (handle == NULL
  41. || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL)
  42. || ((unwind_getip = dlsym (handle, "_Unwind_GetIP")) == NULL)) {
  43. printf(LIBGCC_S_SO " must be installed for backtrace to work\n");
  44. abort();
  45. }
  46. }
  47. #else
  48. # define unwind_backtrace _Unwind_Backtrace
  49. # define unwind_getip _Unwind_GetIP
  50. #endif
  51. static _Unwind_Reason_Code
  52. backtrace_helper (struct _Unwind_Context *ctx, void *a)
  53. {
  54. struct trace_arg *arg = a;
  55. assert (unwind_getip != NULL);
  56. /* We are first called with address in the __backtrace function. Skip it. */
  57. if (arg->cnt != -1)
  58. arg->array[arg->cnt] = (void *) unwind_getip (ctx);
  59. if (++arg->cnt == arg->size)
  60. return _URC_END_OF_STACK;
  61. return _URC_NO_REASON;
  62. }
  63. /*
  64. * Perform stack unwinding by using the _Unwind_Backtrace.
  65. *
  66. */
  67. int backtrace (void **array, int size)
  68. {
  69. struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
  70. #ifdef SHARED
  71. if (unwind_backtrace == NULL)
  72. backtrace_init();
  73. #endif
  74. if (size >= 1)
  75. unwind_backtrace (backtrace_helper, &arg);
  76. return arg.cnt != -1 ? arg.cnt : 0;
  77. }