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 
15 #include <libgcc_s.h>
16 #include <execinfo.h>
17 #include <dlfcn.h>
18 #include <stdlib.h>
19 #include <unwind.h>
20 #include <assert.h>
21 #include <stdio.h>
22 
23 struct trace_arg
24 {
25   void **array;
26   int cnt, size;
27 };
28 
29 #ifdef SHARED
30 static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
31 static _Unwind_VRS_Result (*unwind_vrs_get) (_Unwind_Context *,
32 					     _Unwind_VRS_RegClass,
33 					     _uw,
34 					     _Unwind_VRS_DataRepresentation,
35 					     void *);
36 
backtrace_init(void)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_vrs_get = dlsym (handle, "_Unwind_VRS_Get")) == 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_vrs_get _Unwind_VRS_Get
50 #endif
51 /* This function is identical to "_Unwind_GetGR", except that it uses
52    "unwind_vrs_get" instead of "_Unwind_VRS_Get".  */
53 static inline _Unwind_Word
unwind_getgr(_Unwind_Context * context,int regno)54 unwind_getgr (_Unwind_Context *context, int regno)
55 {
56   _uw val;
57   unwind_vrs_get (context, _UVRSC_CORE, regno, _UVRSD_UINT32, &val);
58   return val;
59 }
60 
61 /* This macro is identical to the _Unwind_GetIP macro, except that it
62    uses "unwind_getgr" instead of "_Unwind_GetGR".  */
63 #define unwind_getip(context) \
64  (unwind_getgr (context, 15) & ~(_Unwind_Word)1)
65 
66 static _Unwind_Reason_Code
backtrace_helper(struct _Unwind_Context * ctx,void * a)67 backtrace_helper (struct _Unwind_Context *ctx, void *a)
68 {
69 	struct trace_arg *arg = a;
70 
71 	assert (unwind_getip(ctx) != NULL);
72 
73 	/* We are first called with address in the __backtrace function. Skip it. */
74 	if (arg->cnt != -1)
75 		arg->array[arg->cnt] = (void *) unwind_getip (ctx);
76 	if (++arg->cnt == arg->size)
77 		return _URC_END_OF_STACK;
78 	return _URC_NO_REASON;
79 }
80 
81 /*
82  * Perform stack unwinding by using the _Unwind_Backtrace.
83  *
84  */
backtrace(void ** array,int size)85 int backtrace (void **array, int size)
86 {
87 	struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
88 
89 #ifdef SHARED
90 	if (unwind_backtrace == NULL)
91 		backtrace_init();
92 #endif
93 
94 	if (size >= 1)
95 		unwind_backtrace (backtrace_helper, &arg);
96 
97 	return arg.cnt != -1 ? arg.cnt : 0;
98 }
99