OSDN Git Service

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