backtrace.c 2.0 KB

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