OSDN Git Service

2007-04-20 Eric Botcazou <ebotcazou@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-2006, AdaCore                     *
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 __alpha_vxworks
50 #include "vxWorks.h"
51 #endif
52
53 #ifdef IN_RTS
54 #define POSIX
55 #include "tconfig.h"
56 #include "tsystem.h"
57 #else
58 #include "config.h"
59 #include "system.h"
60 #endif
61
62 extern int __gnat_backtrace (void **, int, void *, void *, int);
63
64 /* The point is to provide an implementation of the __gnat_backtrace function
65    above, called by the default implementation of the System.Traceback package.
66
67    We first have a series of target specific implementations, each included
68    from a separate C file for readability purposes.
69
70    Then come two flavors of a generic implementation: one relying on static
71    assumptions about the frame layout, and the other one using the GCC EH
72    infrastructure.  The former uses a whole set of macros and structures which
73    may be tailored on a per target basis, and is activated as soon as
74    USE_GENERIC_UNWINDER is defined.  The latter uses a small subset of the
75    macro definitions and is activated when USE_GCC_UNWINDER is defined. It is
76    only available post GCC 3.3.
77
78    Finally, there is a default dummy implementation, necessary to make the
79    linker happy on platforms where the feature is not supported, but where the
80    function is still referenced by the default System.Traceback.  */
81
82 #define Lock_Task system__soft_links__lock_task
83 extern void (*Lock_Task) (void);
84
85 #define Unlock_Task system__soft_links__unlock_task
86 extern void (*Unlock_Task) (void);
87
88 /*-------------------------------------*
89  *-- Target specific implementations --*
90  *-------------------------------------*/
91
92 #if defined (__alpha_vxworks)
93
94 #include "tb-alvxw.c"
95
96 #elif defined (__ALPHA) && defined (__VMS__)
97
98 #include "tb-alvms.c"
99
100 #else
101 /* No target specific implementation.  */
102
103 /*----------------------------------------------------------------*
104  *-- Target specific definitions for the generic implementation --*
105  *----------------------------------------------------------------*/
106
107 /* The stack layout is specified by the target ABI. The "generic" scheme is
108    based on the following assumption:
109
110      The stack layout from some frame pointer is such that the information
111      required to compute the backtrace is available at static offsets.
112
113    For a given frame, the information we are interested in is the saved return
114    address (somewhere after the call instruction in the caller) and a pointer
115    to the caller's frame. The former is the base of the call chain information
116    we store in the tracebacks array. The latter allows us to loop over the
117    successive frames in the chain.
118
119    To initiate the process, we retrieve an initial frame address using the
120    appropriate GCC builtin (__builtin_frame_address).
121
122    This scheme is unfortunately not applicable on every target because the
123    stack layout is not necessarily regular (static) enough. On targets where
124    this scheme applies, the implementation relies on the following items:
125
126    o struct layout, describing the expected stack data layout relevant to the
127      information we are interested in,
128
129    o FRAME_OFFSET, the offset, from a given frame address or frame pointer
130      value, at which this layout will be found,
131
132    o FRAME_LEVEL, controls how many frames up we get at to start with,
133      from the initial frame pointer we compute by way of the GCC builtin,
134
135      0 is most often the appropriate value. 1 may be necessary on targets
136      where return addresses are saved by a function in it's caller's frame
137      (e.g. PPC).
138
139    o PC_ADJUST, to account for the difference between a call point (address
140      of a call instruction), which is what we want in the output array, and
141      the associated return address, which is what we retrieve from the stack.
142
143    o STOP_FRAME, to decide wether we reached the top of the call chain, and
144      thus if the process shall stop.
145
146            :
147            :                   stack
148            |             +----------------+
149            |   +-------->|       :        |
150            |   |         | (FRAME_OFFSET) |
151            |   |         |       :        |  (PC_ADJUST)
152            |   |  layout:| return_address ----------------+
153            |   |         |     ....       |               |
154            +---------------  next_frame   |               |
155                |         |     ....       |               |
156                |         |                |               |
157                |         +----------------+               |  +-----+
158                |         |       :        |<- Base fp     |  |  :  |
159                |         | (FRAME_OFFSET) | (FRAME_LEVEL) |  |  :  |
160                |         |       :        |               +--->    | [1]
161                |  layout:| return_address -------------------->    | [0]
162                |         |       ...      |  (PC_ADJUST)     +-----+
163                +----------   next_frame   |                 traceback[]
164                          |       ...      |
165                          |                |
166                          +----------------+
167
168    o BASE_SKIP,
169
170    Since we inherently deal with return addresses, there is an implicit shift
171    by at least one for the initial point we are able to observe in the chain.
172
173    On some targets (e.g. sparc-solaris), the first return address we can
174    easily get without special code is even our caller's return address, so
175    there is a initial shift of two.
176
177    BASE_SKIP represents this initial shift, which is the minimal "skip_frames"
178    value we support. We could add special code for the skip_frames < BASE_SKIP
179    cases. This is not done currently because there is virtually no situation
180    in which this would be useful.
181
182    Finally, to account for some ABI specificities, a target may (but does
183    not have to) define:
184
185    o FORCE_CALL, to force a call to a dummy function at the very beginning
186      of the computation. See the PPC AIX target for an example where this
187      is useful.
188
189    o FETCH_UP_FRAME, to force an invocation of __builtin_frame_address with a
190      positive argument right after a possibly forced call even if FRAME_LEVEL
191      is 0. See the SPARC Solaris case for an example where this is useful.
192
193   */
194
195 /*--------------------------- PPC AIX/Darwin ----------------------------*/
196
197 #if ((defined (_POWER) && defined (_AIX)) || \
198 (defined (__ppc__) && defined (__APPLE__)))
199
200 #define USE_GENERIC_UNWINDER
201
202 struct layout
203 {
204   struct layout *next;
205   void *pad;
206   void *return_address;
207 };
208
209 #define FRAME_OFFSET(FP) 0
210 #define PC_ADJUST -4
211 #define STOP_FRAME(CURRENT, TOP_STACK) ((void *) (CURRENT) < (TOP_STACK))
212
213 /* The PPC ABI has an interesting specificity: the return address saved by a
214    function is located in it's caller's frame, and the save operation only
215    takes place if the function performs a call.
216
217    To have __gnat_backtrace retrieve its own return address, we then
218    define ... */
219
220 #define FORCE_CALL 1
221 #define FRAME_LEVEL 1
222
223 #define BASE_SKIP 1
224
225 /*---------------------------- PPC VxWorks------------------------------*/
226
227 #elif defined (_ARCH_PPC) && defined (__vxworks)
228
229 #define USE_GENERIC_UNWINDER
230
231 struct layout
232 {
233   struct layout *next;
234   void *return_address;
235 };
236
237 #define FORCE_CALL 1
238 #define FRAME_LEVEL 1
239 /* See the PPC AIX case for an explanation of these values.  */
240
241 #define FRAME_OFFSET(FP) 0
242 #define PC_ADJUST -4
243 #define STOP_FRAME(CURRENT, TOP_STACK) ((CURRENT)->next == 0)
244
245 #define BASE_SKIP 1
246
247 /*-------------------------- SPARC Solaris -----------------------------*/
248
249 #elif defined (sun) && defined (sparc)
250
251 #define USE_GENERIC_UNWINDER
252
253 /* These definitions are inspired from the Appendix D (Software
254    Considerations) of the SPARC V8 architecture manual.  */
255
256 struct layout
257 {
258   struct layout *next;
259   void *return_address;
260 };
261
262 #ifdef __arch64__
263 #define STACK_BIAS 2047 /* V9 ABI */
264 #else
265 #define STACK_BIAS 0    /* V8 ABI */
266 #endif
267
268 #define FRAME_LEVEL 0
269 #define FRAME_OFFSET(FP) (14 * sizeof (void*) + (FP ? STACK_BIAS : 0))
270 #define PC_ADJUST 0
271 #define STOP_FRAME(CURRENT, TOP_STACK) \
272   ((CURRENT)->return_address == 0|| (CURRENT)->next == 0 \
273    || (void *) (CURRENT) < (TOP_STACK))
274
275 /* The SPARC register windows need to be flushed before we may access them
276    from the stack. This is achieved by way of builtin_frame_address only
277    when the "count" argument is positive, so force at least one such call.  */
278 #define FETCH_UP_FRAME_ADDRESS
279
280 #define BASE_SKIP 2
281 /* From the frame pointer of frame N, we are accessing the flushed register
282    window of frame N-1 (positive offset from fp), in which we retrieve the
283    saved return address. We then end up with our caller's return address.  */
284
285 /*------------------------------- x86 ----------------------------------*/
286
287 #elif defined (i386)
288
289 #ifdef __WIN32
290 #include <windows.h>
291 #define IS_BAD_PTR(ptr) (IsBadCodePtr((void *)ptr))
292 #else
293 #define IS_BAD_PTR(ptr) 0
294 #endif
295
296 #define USE_GENERIC_UNWINDER
297
298 struct layout
299 {
300   struct layout *next;
301   void *return_address;
302 };
303
304 #define LOWEST_ADDR 0
305 #define FRAME_LEVEL 1
306 /* builtin_frame_address (1) is expected to work on this target, and (0) might
307    return the soft stack pointer, which does not designate a location where a
308    backchain and a return address might be found.  */
309
310 #define FRAME_OFFSET(FP) 0
311 #define PC_ADJUST -2
312 #define STOP_FRAME(CURRENT, TOP_STACK) \
313   (IS_BAD_PTR((long)(CURRENT)->return_address) \
314    || (unsigned int)(CURRENT)->return_address < LOWEST_ADDR \
315    || (CURRENT)->return_address == 0|| (CURRENT)->next == 0  \
316    || (void *) (CURRENT) < (TOP_STACK))
317
318 #define BASE_SKIP (1+FRAME_LEVEL)
319
320 /* On i386 architecture we check that at the call point we really have a call
321    insn. Possible call instructions are:
322
323    call  addr16        E8 xx xx xx xx
324    call  reg           FF Dx
325    call  off(reg)      FF xx xx
326    lcall addr seg      9A xx xx xx xx xx xx
327
328    This check will not catch all cases but it will increase the backtrace
329    reliability on this architecture.
330 */
331
332 #define VALID_STACK_FRAME(ptr) \
333    (!IS_BAD_PTR(ptr) \
334     && (((*((ptr) - 3) & 0xff) == 0xe8) \
335         || ((*((ptr) - 5) & 0xff) == 0x9a) \
336         || ((*((ptr) - 1) & 0xff) == 0xff) \
337         || (((*(ptr) & 0xd0ff) == 0xd0ff))))
338
339 /*----------------------------- x86_64 ---------------------------------*/
340
341 #elif defined (__x86_64__)
342
343 #define USE_GCC_UNWINDER
344 /* The generic unwinder is not used for this target because it is based
345    on frame layout assumptions that are not reliable on this target (the
346    rbp register is very likely used for something else than storing the
347    frame pointer in optimized code). Hence, we use the GCC unwinder
348    based on DWARF 2 call frame information, although it has the drawback
349    of not being able to unwind through frames compiled without DWARF 2
350    information.
351 */
352
353 #define PC_ADJUST -2
354 /* The minimum size of call instructions on this architecture is 2 bytes */
355
356 /*----------------------------- ia64 ---------------------------------*/
357
358 #elif defined (__ia64__) && (defined (linux) || defined (__hpux__))
359
360 #define USE_GCC_UNWINDER
361 /* Use _Unwind_Backtrace driven exceptions on ia64 HP-UX and ia64
362    GNU/Linux, where _Unwind_Backtrace is provided by the system unwind
363    library. On HP-UX 11.23 this requires patch PHSS_33352, which adds
364    _Unwind_Backtrace to the system unwind library. */
365
366 #define PC_ADJUST -4
367
368
369 #endif
370
371 /*---------------------------------------------------------------------*
372  *--      The post GCC 3.3 infrastructure based implementation       --*
373  *---------------------------------------------------------------------*/
374
375 #if defined (USE_GCC_UNWINDER) && (__GNUC__ * 10 + __GNUC_MINOR__ > 33)
376
377 /* Conditioning the inclusion on the GCC version is useful to avoid bootstrap
378    path problems, since the included file refers to post 3.3 functions in
379    libgcc, and the stage1 compiler is unlikely to be linked against a post 3.3
380    library.  It actually disables the support for backtraces in this compiler
381    for targets defining USE_GCC_UNWINDER, which is OK since we don't use the
382    traceback capability in the compiler anyway.
383
384    The condition is expressed the way above because we cannot reliably rely on
385    any other macro from the base compiler when compiling stage1.  */
386
387 #include "tb-gcc.c"
388
389 /*------------------------------------------------------------------*
390  *-- The generic implementation based on frame layout assumptions --*
391  *------------------------------------------------------------------*/
392
393 #elif defined (USE_GENERIC_UNWINDER)
394
395 #ifndef CURRENT_STACK_FRAME
396 # define CURRENT_STACK_FRAME  ({ char __csf; &__csf; })
397 #endif
398
399 #ifndef VALID_STACK_FRAME
400 #define VALID_STACK_FRAME(ptr) 1
401 #endif
402
403 #ifndef MAX
404 #define MAX(x,y) ((x) > (y) ? (x) : (y))
405 #endif
406
407 #ifndef FORCE_CALL
408 #define FORCE_CALL 0
409 #endif
410
411 /* Make sure the function is not inlined.  */
412 static void forced_callee (void) __attribute__ ((noinline));
413
414 static void forced_callee (void)
415 {
416   /* Make sure the function is not pure.  */
417   volatile int i __attribute__ ((unused)) = 0;
418 }
419
420 int
421 __gnat_backtrace (void **array,
422                   int size,
423                   void *exclude_min,
424                   void *exclude_max,
425                   int skip_frames)
426 {
427   struct layout *current;
428   void *top_frame;
429   void *top_stack;
430   int cnt = 0;
431
432   if (FORCE_CALL)
433     forced_callee ();
434
435   /* Force a call to builtin_frame_address with a positive argument
436      if required. This is necessary e.g. on SPARC to have the register
437      windows flushed before we attempt to access them on the stack.  */
438 #if defined (FETCH_UP_FRAME_ADDRESS) && (FRAME_LEVEL == 0)
439   __builtin_frame_address (1);
440 #endif
441
442   top_frame = __builtin_frame_address (FRAME_LEVEL);
443   top_stack = CURRENT_STACK_FRAME;
444   current = (struct layout *) ((size_t) top_frame + FRAME_OFFSET (0));
445
446   /* Skip the number of calls we have been requested to skip, accounting for
447      the BASE_SKIP parameter.
448
449      FRAME_LEVEL is meaningless for the count adjustment. It impacts where we
450      start retrieving data from, but how many frames "up" we start at is in
451      BASE_SKIP by definition.  */
452
453   skip_frames = MAX (0, skip_frames - BASE_SKIP);
454
455   while (cnt < skip_frames)
456     {
457       current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
458       cnt++;
459     }
460
461   cnt = 0;
462   while (cnt < size)
463     {
464       if (STOP_FRAME (current, top_stack) ||
465           !VALID_STACK_FRAME((char *)(current->return_address + PC_ADJUST)))
466         break;
467
468       if (current->return_address < exclude_min
469           || current->return_address > exclude_max)
470         array[cnt++] = current->return_address + PC_ADJUST;
471
472       current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
473     }
474
475   return cnt;
476 }
477
478 #else
479
480 /* No target specific implementation and neither USE_GCC_UNWINDER not
481    USE_GCC_UNWINDER defined.  */
482
483 /*------------------------------*
484  *-- The dummy implementation --*
485  *------------------------------*/
486
487 int
488 __gnat_backtrace (array, size, exclude_min, exclude_max, skip_frames)
489      void **array ATTRIBUTE_UNUSED;
490      int size ATTRIBUTE_UNUSED;
491      void *exclude_min ATTRIBUTE_UNUSED;
492      void *exclude_max ATTRIBUTE_UNUSED;
493      int skip_frames ATTRIBUTE_UNUSED;
494 {
495   return 0;
496 }
497
498 #endif
499
500 #endif