]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/uclibc/lib/contrib/uclibc/libubacktrace/backtrace.c
update
[l4.git] / l4 / pkg / uclibc / lib / contrib / uclibc / libubacktrace / backtrace.c
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 <libgcc_s.h>
24 #include <execinfo.h>
25 #include <dlfcn.h>
26 #include <stdlib.h>
27 #include <unwind.h>
28 #include <assert.h>
29 #include <stdio.h>
30
31 struct trace_arg
32 {
33   void **array;
34   int cnt, size;
35 };
36
37 #ifdef SHARED
38 static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
39 static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *);
40
41 static void backtrace_init (void)
42 {
43         void *handle = dlopen (LIBGCC_S_SO, RTLD_LAZY);
44
45         if (handle == NULL
46                 || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL)
47                 || ((unwind_getip = dlsym (handle, "_Unwind_GetIP")) == NULL)) {
48                 printf(LIBGCC_S_SO " must be installed for backtrace to work\n");
49                 abort();
50         }
51 }
52 #else
53 # define unwind_backtrace _Unwind_Backtrace
54 # define unwind_getip _Unwind_GetIP
55 #endif
56
57 static _Unwind_Reason_Code
58 backtrace_helper (struct _Unwind_Context *ctx, void *a)
59 {
60         struct trace_arg *arg = a;
61
62         assert (unwind_getip != NULL);
63
64         /* We are first called with address in the __backtrace function. Skip it. */
65         if (arg->cnt != -1)
66                 arg->array[arg->cnt] = (void *) unwind_getip (ctx);
67         if (++arg->cnt == arg->size)
68                 return _URC_END_OF_STACK;
69         return _URC_NO_REASON;
70 }
71
72 /*
73  * Perform stack unwinding by using the _Unwind_Backtrace.
74  *
75  */
76 int backtrace (void **array, int size)
77 {
78         struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
79
80 #ifdef SHARED
81         if (unwind_backtrace == NULL)
82                 backtrace_init();
83 #endif
84
85         if (size >= 1)
86                 unwind_backtrace (backtrace_helper, &arg);
87
88         return arg.cnt != -1 ? arg.cnt : 0;
89 }