backtrace.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
  35. static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *);
  36. static void backtrace_init (void)
  37. {
  38. void *handle = dlopen (LIBGCC_S_SO, RTLD_LAZY);
  39. if (handle == NULL
  40. || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL)
  41. || ((unwind_getip = dlsym (handle, "_Unwind_GetIP")) == NULL)) {
  42. printf(LIBGCC_S_SO " must be installed for backtrace to work\n");
  43. abort();
  44. }
  45. }
  46. static _Unwind_Reason_Code
  47. backtrace_helper (struct _Unwind_Context *ctx, void *a)
  48. {
  49. struct trace_arg *arg = a;
  50. assert (unwind_getip != NULL);
  51. /* We are first called with address in the __backtrace function. Skip it. */
  52. if (arg->cnt != -1)
  53. arg->array[arg->cnt] = (void *) unwind_getip (ctx);
  54. if (++arg->cnt == arg->size)
  55. return _URC_END_OF_STACK;
  56. return _URC_NO_REASON;
  57. }
  58. /*
  59. * Perform stack unwinding by using the _Unwind_Backtrace.
  60. *
  61. */
  62. int backtrace (void **array, int size)
  63. {
  64. struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
  65. if (unwind_backtrace == NULL)
  66. backtrace_init();
  67. if (size >= 1)
  68. unwind_backtrace (backtrace_helper, &arg);
  69. return arg.cnt != -1 ? arg.cnt : 0;
  70. }