lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 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 | |
| 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 | |
| 30 | struct trace_arg |
| 31 | { |
| 32 | void **array; |
| 33 | int cnt, size; |
| 34 | }; |
| 35 | |
| 36 | static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *); |
| 37 | static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *); |
| 38 | |
| 39 | static void backtrace_init (void) |
| 40 | { |
| 41 | void *handle = dlopen ("libgcc_s.so.1", RTLD_LAZY); |
| 42 | |
| 43 | if (handle == NULL |
| 44 | || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL) |
| 45 | || ((unwind_getip = dlsym (handle, "_Unwind_GetIP")) == NULL)) { |
| 46 | printf("libgcc_s.so.1 must be installed for backtrace to work\n"); |
| 47 | abort(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | static _Unwind_Reason_Code |
| 52 | backtrace_helper (struct _Unwind_Context *ctx, void *a) |
| 53 | { |
| 54 | struct trace_arg *arg = a; |
| 55 | |
| 56 | assert (unwind_getip != NULL); |
| 57 | |
| 58 | /* We are first called with address in the __backtrace function. Skip it. */ |
| 59 | if (arg->cnt != -1) |
| 60 | arg->array[arg->cnt] = (void *) unwind_getip (ctx); |
| 61 | if (++arg->cnt == arg->size) |
| 62 | return _URC_END_OF_STACK; |
| 63 | return _URC_NO_REASON; |
| 64 | } |
| 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 | |
| 74 | if (unwind_backtrace == NULL) |
| 75 | backtrace_init(); |
| 76 | |
| 77 | if (size >= 1) |
| 78 | unwind_backtrace (backtrace_helper, &arg); |
| 79 | |
| 80 | return arg.cnt != -1 ? arg.cnt : 0; |
| 81 | } |