OSDN Git Service

2011-09-27 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / tracebak.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                            T R A C E B A C K                             *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *            Copyright (C) 2000-2011, Free Software Foundation, Inc.       *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 2,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License *
17  * for  more details.  You should have  received  a copy of the GNU General *
18  * Public License  distributed with GNAT;  see file COPYING.  If not, write *
19  * to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, *
20  * Boston, MA 02110-1301, USA.                                              *
21  *                                                                          *
22  * As a  special  exception,  if you  link  this file  with other  files to *
23  * produce an executable,  this file does not by itself cause the resulting *
24  * executable to be covered by the GNU General Public License. This except- *
25  * ion does not  however invalidate  any other reasons  why the  executable *
26  * file might be covered by the  GNU Public License.                        *
27  *                                                                          *
28  * GNAT was originally developed  by the GNAT team at  New York University. *
29  * Extensive contributions were provided by Ada Core Technologies Inc.      *
30  *                                                                          *
31  ****************************************************************************/
32
33 /* This file contains low level support for stack unwinding using GCC intrinsic
34    functions.
35    It has been tested on the following configurations:
36    PowerPC/AiX
37    PowerPC/Darwin
38    PowerPC/VxWorks
39    SPARC/Solaris
40    i386/GNU/Linux
41    i386/Solaris
42    i386/NT
43    i386/OS2
44    i386/LynxOS
45    Alpha/VxWorks
46    Alpha/VMS
47 */
48
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
52
53 #ifdef __alpha_vxworks
54 #include "vxWorks.h"
55 #endif
56
57 #ifdef IN_RTS
58 #define POSIX
59 #include "tconfig.h"
60 #include "tsystem.h"
61 #else
62 #include "config.h"
63 #include "system.h"
64 /* We don't want fancy_abort here.  */
65 #undef abort
66 #endif
67
68 extern int __gnat_backtrace (void **, int, void *, void *, int);
69
70 /* The point is to provide an implementation of the __gnat_backtrace function
71    above, called by the default implementation of the System.Traceback package.
72
73    We first have a series of target specific implementations, each included
74    from a separate C file for readability purposes.
75
76    Then come two flavors of a generic implementation: one relying on static
77    assumptions about the frame layout, and the other one using the GCC EH
78    infrastructure.  The former uses a whole set of macros and structures which
79    may be tailored on a per target basis, and is activated as soon as
80    USE_GENERIC_UNWINDER is defined.  The latter uses a small subset of the
81    macro definitions and is activated when USE_GCC_UNWINDER is defined. It is
82    only available post GCC 3.3.
83
84    Finally, there is a default dummy implementation, necessary to make the
85    linker happy on platforms where the feature is not supported, but where the
86    function is still referenced by the default System.Traceback.  */
87
88 #define Lock_Task system__soft_links__lock_task
89 extern void (*Lock_Task) (void);
90
91 #define Unlock_Task system__soft_links__unlock_task
92 extern void (*Unlock_Task) (void);
93
94 /*-------------------------------------*
95  *-- Target specific implementations --*
96  *-------------------------------------*/
97
98 #if defined (__alpha_vxworks)
99
100 #include "tb-alvxw.c"
101
102 #elif defined (__ALPHA) && defined (__VMS__)
103
104 #include "tb-alvms.c"
105
106 #elif defined (__ia64__) && defined (__VMS__)
107
108 #include "tb-ivms.c"
109
110 #else
111
112 /* No target specific implementation.  */
113
114 /*----------------------------------------------------------------*
115  *-- Target specific definitions for the generic implementation --*
116  *----------------------------------------------------------------*/
117
118 /* The stack layout is specified by the target ABI. The "generic" scheme is
119    based on the following assumption:
120
121      The stack layout from some frame pointer is such that the information
122      required to compute the backtrace is available at static offsets.
123
124    For a given frame, the information we are interested in is the saved return
125    address (somewhere after the call instruction in the caller) and a pointer
126    to the caller's frame. The former is the base of the call chain information
127    we store in the tracebacks array. The latter allows us to loop over the
128    successive frames in the chain.
129
130    To initiate the process, we retrieve an initial frame address using the
131    appropriate GCC builtin (__builtin_frame_address).
132
133    This scheme is unfortunately not applicable on every target because the
134    stack layout is not necessarily regular (static) enough. On targets where
135    this scheme applies, the implementation relies on the following items:
136
137    o struct layout, describing the expected stack data layout relevant to the
138      information we are interested in,
139
140    o FRAME_OFFSET, the offset, from a given frame address or frame pointer
141      value, at which this layout will be found,
142
143    o FRAME_LEVEL, controls how many frames up we get at to start with,
144      from the initial frame pointer we compute by way of the GCC builtin,
145
146      0 is most often the appropriate value. 1 may be necessary on targets
147      where return addresses are saved by a function in it's caller's frame
148      (e.g. PPC).
149
150    o PC_ADJUST, to account for the difference between a call point (address
151      of a call instruction), which is what we want in the output array, and
152      the associated return address, which is what we retrieve from the stack.
153
154    o STOP_FRAME, to decide whether we reached the top of the call chain, and
155      thus if the process shall stop.
156
157            :
158            :                   stack
159            |             +----------------+
160            |   +-------->|       :        |
161            |   |         | (FRAME_OFFSET) |
162            |   |         |       :        |  (PC_ADJUST)
163            |   |  layout:| return_address ----------------+
164            |   |         |     ....       |               |
165            +---------------  next_frame   |               |
166                |         |     ....       |               |
167                |         |                |               |
168                |         +----------------+               |  +-----+
169                |         |       :        |<- Base fp     |  |  :  |
170                |         | (FRAME_OFFSET) | (FRAME_LEVEL) |  |  :  |
171                |         |       :        |               +--->    | [1]
172                |  layout:| return_address -------------------->    | [0]
173                |         |       ...      |  (PC_ADJUST)     +-----+
174                +----------   next_frame   |                 traceback[]
175                          |       ...      |
176                          |                |
177                          +----------------+
178
179    o BASE_SKIP,
180
181    Since we inherently deal with return addresses, there is an implicit shift
182    by at least one for the initial point we are able to observe in the chain.
183
184    On some targets (e.g. sparc-solaris), the first return address we can
185    easily get without special code is even our caller's return address, so
186    there is a initial shift of two.
187
188    BASE_SKIP represents this initial shift, which is the minimal "skip_frames"
189    value we support. We could add special code for the skip_frames < BASE_SKIP
190    cases. This is not done currently because there is virtually no situation
191    in which this would be useful.
192
193    Finally, to account for some ABI specificities, a target may (but does
194    not have to) define:
195
196    o FORCE_CALL, to force a call to a dummy function at the very beginning
197      of the computation. See the PPC AIX target for an example where this
198      is useful.
199
200    o FETCH_UP_FRAME, to force an invocation of __builtin_frame_address with a
201      positive argument right after a possibly forced call even if FRAME_LEVEL
202      is 0. See the SPARC Solaris case for an example where this is useful.
203
204   */
205
206 /*------------------- Darwin 8 (OSX 10.4) or newer ----------------------*/
207 #if defined (__APPLE__) \
208     && defined (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) \
209     && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1040
210  
211 #define USE_GCC_UNWINDER
212
213 #if defined (__i386__) || defined (__x86_64__)
214 #define PC_ADJUST -2
215 #elif defined (__ppc__) || defined (__ppc64__)
216 #define PC_ADJUST -4
217 #else
218 #error Unhandled darwin architecture.
219 #endif
220
221 /*------------------------ PPC AIX/Older Darwin -------------------------*/
222 #elif ((defined (_POWER) && defined (_AIX)) || \
223 (defined (__ppc__) && defined (__APPLE__)))
224
225 #define USE_GENERIC_UNWINDER
226
227 struct layout
228 {
229   struct layout *next;
230   void *pad;
231   void *return_address;
232 };
233
234 #define FRAME_OFFSET(FP) 0
235 #define PC_ADJUST -4
236
237 /* Eventhough the base PPC ABI states that a toplevel frame entry
238    should to feature a null backchain, AIX might expose a null return
239    address instead.  */
240
241 #define STOP_FRAME(CURRENT, TOP_STACK) \
242   (((void *) (CURRENT) < (TOP_STACK)) \
243    || (CURRENT)->return_address == NULL)
244
245 /* The PPC ABI has an interesting specificity: the return address saved by a
246    function is located in it's caller's frame, and the save operation only
247    takes place if the function performs a call.
248
249    To have __gnat_backtrace retrieve its own return address, we then
250    define ... */
251
252 #define FORCE_CALL 1
253 #define FRAME_LEVEL 1
254
255 #define BASE_SKIP 1
256
257 /*-------------------- PPC ELF (GNU/Linux & VxWorks) ---------------------*/
258
259 #elif (defined (_ARCH_PPC) && defined (__vxworks)) ||  \
260   (defined (linux) && defined (__powerpc__))
261
262 #define USE_GENERIC_UNWINDER
263
264 struct layout
265 {
266   struct layout *next;
267   void *return_address;
268 };
269
270 #define FORCE_CALL 1
271 #define FRAME_LEVEL 1
272 /* See the PPC AIX case for an explanation of these values.  */
273
274 #define FRAME_OFFSET(FP) 0
275 #define PC_ADJUST -4
276
277 /* According to the base PPC ABI, a toplevel frame entry should feature
278    a null backchain.  What happens at signal handler frontiers isn't so
279    well specified, so we add a safety guard on top.  */
280
281 #define STOP_FRAME(CURRENT, TOP_STACK) \
282  ((CURRENT)->next == 0 || ((long)(CURRENT)->next % __alignof__(void*)) != 0)
283
284 #define BASE_SKIP 1
285
286 /*-------------------------- SPARC Solaris -----------------------------*/
287
288 #elif defined (sun) && defined (sparc)
289
290 #define USE_GENERIC_UNWINDER
291
292 /* These definitions are inspired from the Appendix D (Software
293    Considerations) of the SPARC V8 architecture manual.  */
294
295 struct layout
296 {
297   struct layout *next;
298   void *return_address;
299 };
300
301 #ifdef __arch64__
302 #define STACK_BIAS 2047 /* V9 ABI */
303 #else
304 #define STACK_BIAS 0    /* V8 ABI */
305 #endif
306
307 #define FRAME_LEVEL 0
308 #define FRAME_OFFSET(FP) (14 * sizeof (void*) + (FP ? STACK_BIAS : 0))
309 #define PC_ADJUST 0
310 #define STOP_FRAME(CURRENT, TOP_STACK) \
311   ((CURRENT)->return_address == 0|| (CURRENT)->next == 0 \
312    || (void *) (CURRENT) < (TOP_STACK))
313
314 /* The SPARC register windows need to be flushed before we may access them
315    from the stack. This is achieved by way of builtin_frame_address only
316    when the "count" argument is positive, so force at least one such call.  */
317 #define FETCH_UP_FRAME_ADDRESS
318
319 #define BASE_SKIP 2
320 /* From the frame pointer of frame N, we are accessing the flushed register
321    window of frame N-1 (positive offset from fp), in which we retrieve the
322    saved return address. We then end up with our caller's return address.  */
323
324 /*------------------------------- x86 ----------------------------------*/
325
326 #elif defined (i386)
327
328 #if defined (__WIN32)
329 #include <windows.h>
330 #define IS_BAD_PTR(ptr) (IsBadCodePtr((void *)ptr))
331 #elif defined (sun)
332 #define IS_BAD_PTR(ptr) ((unsigned long)ptr == -1UL)
333 #else
334 #define IS_BAD_PTR(ptr) 0
335 #endif
336
337 /* Starting with GCC 4.6, -fomit-frame-pointer is turned on by default for
338    32-bit x86/Linux as well and DWARF 2 unwind tables are emitted instead.
339    See the x86-64 case below for the drawbacks with this approach.  */
340 #if defined (linux) && (__GNUC__ * 10 + __GNUC_MINOR__ > 45)
341 #define USE_GCC_UNWINDER
342 #else
343 #define USE_GENERIC_UNWINDER
344 #endif
345
346 struct layout
347 {
348   struct layout *next;
349   void *return_address;
350 };
351
352 #define FRAME_LEVEL 1
353 /* builtin_frame_address (1) is expected to work on this target, and (0) might
354    return the soft stack pointer, which does not designate a location where a
355    backchain and a return address might be found.  */
356
357 #define FRAME_OFFSET(FP) 0
358 #define PC_ADJUST -2
359 #define STOP_FRAME(CURRENT, TOP_STACK) \
360   (IS_BAD_PTR((long)(CURRENT)) \
361    || IS_BAD_PTR((long)(CURRENT)->return_address) \
362    || (CURRENT)->return_address == 0 \
363    || (void *) ((CURRENT)->next) < (TOP_STACK)  \
364    || (void *) (CURRENT) < (TOP_STACK))
365
366 #define BASE_SKIP (1+FRAME_LEVEL)
367
368 /* On i386 architecture we check that at the call point we really have a call
369    insn. Possible call instructions are:
370
371    call  addr16        E8 xx xx xx xx
372    call  reg           FF Dx
373    call  off(reg)      FF xx xx
374    lcall addr seg      9A xx xx xx xx xx xx
375
376    This check will not catch all cases but it will increase the backtrace
377    reliability on this architecture.
378 */
379
380 #define VALID_STACK_FRAME(ptr) \
381    (!IS_BAD_PTR(ptr) \
382     && (((*((ptr) - 3) & 0xff) == 0xe8) \
383         || ((*((ptr) - 5) & 0xff) == 0x9a) \
384         || ((*((ptr) - 1) & 0xff) == 0xff) \
385         || (((*(ptr) & 0xd0ff) == 0xd0ff))))
386
387 /*----------------------------- x86_64 ---------------------------------*/
388
389 #elif defined (__x86_64__)
390
391 #define USE_GCC_UNWINDER
392 /* The generic unwinder is not used for this target because it is based
393    on frame layout assumptions that are not reliable on this target (the
394    rbp register is very likely used for something else than storing the
395    frame pointer in optimized code). Hence, we use the GCC unwinder
396    based on DWARF 2 call frame information, although it has the drawback
397    of not being able to unwind through frames compiled without DWARF 2
398    information.
399 */
400
401 #define PC_ADJUST -2
402 /* The minimum size of call instructions on this architecture is 2 bytes */
403
404 /*----------------------------- ia64 ---------------------------------*/
405
406 #elif defined (__ia64__) && (defined (linux) || defined (__hpux__))
407
408 #define USE_GCC_UNWINDER
409 /* Use _Unwind_Backtrace driven exceptions on ia64 HP-UX and ia64
410    GNU/Linux, where _Unwind_Backtrace is provided by the system unwind
411    library. On HP-UX 11.23 this requires patch PHSS_33352, which adds
412    _Unwind_Backtrace to the system unwind library. */
413
414 #define PC_ADJUST -4
415
416
417 #endif
418
419 /*---------------------------------------------------------------------*
420  *--      The post GCC 3.3 infrastructure based implementation       --*
421  *---------------------------------------------------------------------*/
422
423 #if defined (USE_GCC_UNWINDER) && (__GNUC__ * 10 + __GNUC_MINOR__ > 33)
424
425 /* Conditioning the inclusion on the GCC version is useful to avoid bootstrap
426    path problems, since the included file refers to post 3.3 functions in
427    libgcc, and the stage1 compiler is unlikely to be linked against a post 3.3
428    library.  It actually disables the support for backtraces in this compiler
429    for targets defining USE_GCC_UNWINDER, which is OK since we don't use the
430    traceback capability in the compiler anyway.
431
432    The condition is expressed the way above because we cannot reliably rely on
433    any other macro from the base compiler when compiling stage1.  */
434
435 #include "tb-gcc.c"
436
437 /*------------------------------------------------------------------*
438  *-- The generic implementation based on frame layout assumptions --*
439  *------------------------------------------------------------------*/
440
441 #elif defined (USE_GENERIC_UNWINDER)
442
443 #ifndef CURRENT_STACK_FRAME
444 # define CURRENT_STACK_FRAME  ({ char __csf; &__csf; })
445 #endif
446
447 #ifndef VALID_STACK_FRAME
448 #define VALID_STACK_FRAME(ptr) 1
449 #endif
450
451 #ifndef MAX
452 #define MAX(x,y) ((x) > (y) ? (x) : (y))
453 #endif
454
455 #ifndef FORCE_CALL
456 #define FORCE_CALL 0
457 #endif
458
459 /* Make sure the function is not inlined.  */
460 static void forced_callee (void) __attribute__ ((noinline));
461
462 static void forced_callee (void)
463 {
464   /* Make sure the function is not pure.  */
465   volatile int i __attribute__ ((unused)) = 0;
466 }
467
468 int
469 __gnat_backtrace (void **array,
470                   int size,
471                   void *exclude_min,
472                   void *exclude_max,
473                   int skip_frames)
474 {
475   struct layout *current;
476   void *top_frame;
477   void *top_stack ATTRIBUTE_UNUSED;
478   int cnt = 0;
479
480   if (FORCE_CALL)
481     forced_callee ();
482
483   /* Force a call to builtin_frame_address with a positive argument
484      if required. This is necessary e.g. on SPARC to have the register
485      windows flushed before we attempt to access them on the stack.  */
486 #if defined (FETCH_UP_FRAME_ADDRESS) && (FRAME_LEVEL == 0)
487   __builtin_frame_address (1);
488 #endif
489
490   top_frame = __builtin_frame_address (FRAME_LEVEL);
491   top_stack = CURRENT_STACK_FRAME;
492   current = (struct layout *) ((size_t) top_frame + FRAME_OFFSET (0));
493
494   /* Skip the number of calls we have been requested to skip, accounting for
495      the BASE_SKIP parameter.
496
497      FRAME_LEVEL is meaningless for the count adjustment. It impacts where we
498      start retrieving data from, but how many frames "up" we start at is in
499      BASE_SKIP by definition.  */
500
501   skip_frames = MAX (0, skip_frames - BASE_SKIP);
502
503   while (cnt < skip_frames)
504     {
505       current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
506       cnt++;
507     }
508
509   cnt = 0;
510   while (cnt < size)
511     {
512       if (STOP_FRAME (current, top_stack) ||
513           !VALID_STACK_FRAME(((char *) current->return_address) + PC_ADJUST))
514         break;
515
516       if (current->return_address < exclude_min
517           || current->return_address > exclude_max)
518         array[cnt++] = ((char *) current->return_address) + PC_ADJUST;
519
520       current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
521     }
522
523   return cnt;
524 }
525
526 #else
527
528 /* No target specific implementation and neither USE_GCC_UNWINDER nor
529    USE_GENERIC_UNWINDER defined.  */
530
531 /*------------------------------*
532  *-- The dummy implementation --*
533  *------------------------------*/
534
535 int
536 __gnat_backtrace (void **array ATTRIBUTE_UNUSED,
537                   int size ATTRIBUTE_UNUSED,
538                   void *exclude_min ATTRIBUTE_UNUSED,
539                   void *exclude_max ATTRIBUTE_UNUSED,
540                   int skip_frames ATTRIBUTE_UNUSED)
541 {
542   return 0;
543 }
544
545 #endif
546
547 #endif
548
549 #ifdef __cplusplus
550 }
551 #endif