2013-03-08 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / gcc / ada / tracebak.c
blob4efb75e61f1e70255a1750cd1c907ff467c10e72
1 /****************************************************************************
2 * *
3 * GNAT RUN-TIME COMPONENTS *
4 * *
5 * T R A C E B A C K *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 2000-2012, 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 3, 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. *
17 * *
18 * As a special exception under Section 7 of GPL version 3, you are granted *
19 * additional permissions described in the GCC Runtime Library Exception, *
20 * version 3.1, as published by the Free Software Foundation. *
21 * *
22 * You should have received a copy of the GNU General Public License and *
23 * a copy of the GCC Runtime Library Exception along with this program; *
24 * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see *
25 * <http://www.gnu.org/licenses/>. *
26 * *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
29 * *
30 ****************************************************************************/
32 /* This file contains low level support for stack unwinding using GCC intrinsic
33 functions.
34 It has been tested on the following configurations:
35 PowerPC/AiX
36 PowerPC/Darwin
37 PowerPC/VxWorks
38 PowerPC/LynxOS-178
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
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
53 #ifdef __alpha_vxworks
54 #include "vxWorks.h"
55 #endif
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
68 extern int __gnat_backtrace (void **, int, void *, void *, int);
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.
73 We first have a series of target specific implementations, each included
74 from a separate C file for readability purposes.
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.
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. */
88 #define Lock_Task system__soft_links__lock_task
89 extern void (*Lock_Task) (void);
91 #define Unlock_Task system__soft_links__unlock_task
92 extern void (*Unlock_Task) (void);
94 /*-------------------------------------*
95 *-- Target specific implementations --*
96 *-------------------------------------*/
98 #if defined (__alpha_vxworks)
100 #include "tb-alvxw.c"
102 #elif defined (__ALPHA) && defined (__VMS__)
104 #include "tb-alvms.c"
106 #elif defined (__ia64__) && defined (__VMS__)
108 #include "tb-ivms.c"
110 #elif defined (_WIN64) && defined (__SEH__)
112 #include <windows.h>
115 __gnat_backtrace (void **array,
116 int size,
117 void *exclude_min,
118 void *exclude_max,
119 int skip_frames)
121 CONTEXT context;
122 UNWIND_HISTORY_TABLE history;
123 int i;
125 /* Get the context. */
126 RtlCaptureContext (&context);
128 /* Setup unwind history table (a cached to speed-up unwinding). */
129 memset (&history, 0, sizeof (history));
131 i = 0;
132 while (1)
134 PRUNTIME_FUNCTION RuntimeFunction;
135 KNONVOLATILE_CONTEXT_POINTERS NvContext;
136 ULONG64 ImageBase;
137 VOID *HandlerData;
138 ULONG64 EstablisherFrame;
140 /* Get function metadata. */
141 RuntimeFunction = RtlLookupFunctionEntry
142 (context.Rip, &ImageBase, &history);
144 if (!RuntimeFunction)
146 /* In case of failure, assume this is a leaf function. */
147 context.Rip = *(ULONG64 *) context.Rsp;
148 context.Rsp += 8;
150 else
152 /* Unwind. */
153 memset (&NvContext, 0, sizeof (KNONVOLATILE_CONTEXT_POINTERS));
154 RtlVirtualUnwind (0, ImageBase, context.Rip, RuntimeFunction,
155 &context, &HandlerData, &EstablisherFrame,
156 &NvContext);
159 /* 0 means bottom of the stack. */
160 if (context.Rip == 0)
161 break;
163 /* Skip frames. */
164 if (skip_frames > 1)
166 skip_frames--;
167 continue;
169 /* Excluded frames. */
170 if ((void *)context.Rip >= exclude_min
171 && (void *)context.Rip <= exclude_max)
172 continue;
174 array[i++] = (void *)(context.Rip - 2);
175 if (i >= size)
176 break;
178 return i;
180 #else
182 /* No target specific implementation. */
184 /*----------------------------------------------------------------*
185 *-- Target specific definitions for the generic implementation --*
186 *----------------------------------------------------------------*/
188 /* The stack layout is specified by the target ABI. The "generic" scheme is
189 based on the following assumption:
191 The stack layout from some frame pointer is such that the information
192 required to compute the backtrace is available at static offsets.
194 For a given frame, the information we are interested in is the saved return
195 address (somewhere after the call instruction in the caller) and a pointer
196 to the caller's frame. The former is the base of the call chain information
197 we store in the tracebacks array. The latter allows us to loop over the
198 successive frames in the chain.
200 To initiate the process, we retrieve an initial frame address using the
201 appropriate GCC builtin (__builtin_frame_address).
203 This scheme is unfortunately not applicable on every target because the
204 stack layout is not necessarily regular (static) enough. On targets where
205 this scheme applies, the implementation relies on the following items:
207 o struct layout, describing the expected stack data layout relevant to the
208 information we are interested in,
210 o FRAME_OFFSET, the offset, from a given frame address or frame pointer
211 value, at which this layout will be found,
213 o FRAME_LEVEL, controls how many frames up we get at to start with,
214 from the initial frame pointer we compute by way of the GCC builtin,
216 0 is most often the appropriate value. 1 may be necessary on targets
217 where return addresses are saved by a function in it's caller's frame
218 (e.g. PPC).
220 o PC_ADJUST, to account for the difference between a call point (address
221 of a call instruction), which is what we want in the output array, and
222 the associated return address, which is what we retrieve from the stack.
224 o STOP_FRAME, to decide whether we reached the top of the call chain, and
225 thus if the process shall stop.
228 : stack
229 | +----------------+
230 | +-------->| : |
231 | | | (FRAME_OFFSET) |
232 | | | : | (PC_ADJUST)
233 | | layout:| return_address ----------------+
234 | | | .... | |
235 +--------------- next_frame | |
236 | | .... | |
237 | | | |
238 | +----------------+ | +-----+
239 | | : |<- Base fp | | : |
240 | | (FRAME_OFFSET) | (FRAME_LEVEL) | | : |
241 | | : | +---> | [1]
242 | layout:| return_address --------------------> | [0]
243 | | ... | (PC_ADJUST) +-----+
244 +---------- next_frame | traceback[]
245 | ... |
247 +----------------+
249 o BASE_SKIP,
251 Since we inherently deal with return addresses, there is an implicit shift
252 by at least one for the initial point we are able to observe in the chain.
254 On some targets (e.g. sparc-solaris), the first return address we can
255 easily get without special code is even our caller's return address, so
256 there is a initial shift of two.
258 BASE_SKIP represents this initial shift, which is the minimal "skip_frames"
259 value we support. We could add special code for the skip_frames < BASE_SKIP
260 cases. This is not done currently because there is virtually no situation
261 in which this would be useful.
263 Finally, to account for some ABI specificities, a target may (but does
264 not have to) define:
266 o FORCE_CALL, to force a call to a dummy function at the very beginning
267 of the computation. See the PPC AIX target for an example where this
268 is useful.
270 o FETCH_UP_FRAME, to force an invocation of __builtin_frame_address with a
271 positive argument right after a possibly forced call even if FRAME_LEVEL
272 is 0. See the SPARC Solaris case for an example where this is useful.
276 /*------------------- Darwin 8 (OSX 10.4) or newer ----------------------*/
277 #if defined (__APPLE__) \
278 && defined (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) \
279 && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1040
281 #define USE_GCC_UNWINDER
283 #if defined (__i386__) || defined (__x86_64__)
284 #define PC_ADJUST -2
285 #elif defined (__ppc__) || defined (__ppc64__)
286 #define PC_ADJUST -4
287 #else
288 #error Unhandled darwin architecture.
289 #endif
291 /*---------------------- PPC AIX/PPC Lynx 178/Older Darwin ------------------*/
292 #elif ((defined (_POWER) && defined (_AIX)) || \
293 (defined (__powerpc__) && defined (__Lynx__) && !defined(__ELF__)) || \
294 (defined (__ppc__) && defined (__APPLE__)))
296 #define USE_GENERIC_UNWINDER
298 struct layout
300 struct layout *next;
301 void *pad;
302 void *return_address;
305 #define FRAME_OFFSET(FP) 0
306 #define PC_ADJUST -4
308 /* Eventhough the base PPC ABI states that a toplevel frame entry
309 should to feature a null backchain, AIX might expose a null return
310 address instead. */
312 /* Then LynxOS-178 features yet another variation, with return_address
313 == &<entrypoint>, with two possible entry points (one for the main
314 process and one for threads). Beware that &bla returns the address
315 of a descriptor when "bla" is a function. Getting the code address
316 requires an extra dereference. */
318 #if defined (__Lynx__)
319 extern void __start(); /* process entry point. */
320 extern void __runnit(); /* thread entry point. */
321 #define EXTRA_STOP_CONDITION(CURRENT) \
322 ((CURRENT)->return_address == *(void**)&__start \
323 || (CURRENT)->return_address == *(void**)&__runnit)
324 #else
325 #define EXTRA_STOP_CONDITION(CURRENT) (0)
326 #endif
328 #define STOP_FRAME(CURRENT, TOP_STACK) \
329 (((void *) (CURRENT) < (TOP_STACK)) \
330 || (CURRENT)->return_address == NULL \
331 || EXTRA_STOP_CONDITION(CURRENT))
333 /* The PPC ABI has an interesting specificity: the return address saved by a
334 function is located in it's caller's frame, and the save operation only
335 takes place if the function performs a call.
337 To have __gnat_backtrace retrieve its own return address, we then
338 define ... */
340 #define FORCE_CALL 1
341 #define FRAME_LEVEL 1
343 #define BASE_SKIP 1
345 /*-------------------- PPC ELF (GNU/Linux & VxWorks) ---------------------*/
347 #elif (defined (_ARCH_PPC) && defined (__vxworks)) || \
348 (defined (linux) && defined (__powerpc__))
350 #define USE_GENERIC_UNWINDER
352 struct layout
354 struct layout *next;
355 void *return_address;
358 #define FORCE_CALL 1
359 #define FRAME_LEVEL 1
360 /* See the PPC AIX case for an explanation of these values. */
362 #define FRAME_OFFSET(FP) 0
363 #define PC_ADJUST -4
365 /* According to the base PPC ABI, a toplevel frame entry should feature
366 a null backchain. What happens at signal handler frontiers isn't so
367 well specified, so we add a safety guard on top. */
369 #define STOP_FRAME(CURRENT, TOP_STACK) \
370 ((CURRENT)->next == 0 || ((long)(CURRENT)->next % __alignof__(void*)) != 0)
372 #define BASE_SKIP 1
374 /*-------------------------- SPARC Solaris -----------------------------*/
376 #elif defined (sun) && defined (sparc)
378 #define USE_GENERIC_UNWINDER
380 /* These definitions are inspired from the Appendix D (Software
381 Considerations) of the SPARC V8 architecture manual. */
383 struct layout
385 struct layout *next;
386 void *return_address;
389 #ifdef __arch64__
390 #define STACK_BIAS 2047 /* V9 ABI */
391 #else
392 #define STACK_BIAS 0 /* V8 ABI */
393 #endif
395 #define FRAME_LEVEL 0
396 #define FRAME_OFFSET(FP) (14 * sizeof (void*) + (FP ? STACK_BIAS : 0))
397 #define PC_ADJUST 0
398 #define STOP_FRAME(CURRENT, TOP_STACK) \
399 ((CURRENT)->return_address == 0|| (CURRENT)->next == 0 \
400 || (void *) (CURRENT) < (TOP_STACK))
402 /* The SPARC register windows need to be flushed before we may access them
403 from the stack. This is achieved by way of builtin_frame_address only
404 when the "count" argument is positive, so force at least one such call. */
405 #define FETCH_UP_FRAME_ADDRESS
407 #define BASE_SKIP 2
408 /* From the frame pointer of frame N, we are accessing the flushed register
409 window of frame N-1 (positive offset from fp), in which we retrieve the
410 saved return address. We then end up with our caller's return address. */
412 /*------------------------------- x86 ----------------------------------*/
414 #elif defined (i386)
416 #if defined (__WIN32)
417 #include <windows.h>
418 #define IS_BAD_PTR(ptr) (IsBadCodePtr((FARPROC)ptr))
419 #elif defined (sun)
420 #define IS_BAD_PTR(ptr) ((unsigned long)ptr == -1UL)
421 #else
422 #define IS_BAD_PTR(ptr) 0
423 #endif
425 /* Starting with GCC 4.6, -fomit-frame-pointer is turned on by default for
426 32-bit x86/Linux as well and DWARF 2 unwind tables are emitted instead.
427 See the x86-64 case below for the drawbacks with this approach. */
428 #if defined (linux) && (__GNUC__ * 10 + __GNUC_MINOR__ > 45)
429 #define USE_GCC_UNWINDER
430 #else
431 #define USE_GENERIC_UNWINDER
432 #endif
434 struct layout
436 struct layout *next;
437 void *return_address;
440 #define FRAME_LEVEL 1
441 /* builtin_frame_address (1) is expected to work on this target, and (0) might
442 return the soft stack pointer, which does not designate a location where a
443 backchain and a return address might be found. */
445 #define FRAME_OFFSET(FP) 0
446 #define PC_ADJUST -2
447 #define STOP_FRAME(CURRENT, TOP_STACK) \
448 (IS_BAD_PTR((long)(CURRENT)) \
449 || IS_BAD_PTR((long)(CURRENT)->return_address) \
450 || (CURRENT)->return_address == 0 \
451 || (void *) ((CURRENT)->next) < (TOP_STACK) \
452 || (void *) (CURRENT) < (TOP_STACK))
454 #define BASE_SKIP (1+FRAME_LEVEL)
456 /* On i386 architecture we check that at the call point we really have a call
457 insn. Possible call instructions are:
459 call addr16 E8 xx xx xx xx
460 call reg FF Dx
461 call off(reg) FF xx xx
462 lcall addr seg 9A xx xx xx xx xx xx
464 This check will not catch all cases but it will increase the backtrace
465 reliability on this architecture.
468 #define VALID_STACK_FRAME(ptr) \
469 (!IS_BAD_PTR(ptr) \
470 && (((*((ptr) - 3) & 0xff) == 0xe8) \
471 || ((*((ptr) - 5) & 0xff) == 0x9a) \
472 || ((*((ptr) - 1) & 0xff) == 0xff) \
473 || (((*(ptr) & 0xd0ff) == 0xd0ff))))
475 /*----------------------------- x86_64 ---------------------------------*/
477 #elif defined (__x86_64__)
479 #define USE_GCC_UNWINDER
480 /* The generic unwinder is not used for this target because it is based
481 on frame layout assumptions that are not reliable on this target (the
482 rbp register is very likely used for something else than storing the
483 frame pointer in optimized code). Hence, we use the GCC unwinder
484 based on DWARF 2 call frame information, although it has the drawback
485 of not being able to unwind through frames compiled without DWARF 2
486 information.
489 #define PC_ADJUST -2
490 /* The minimum size of call instructions on this architecture is 2 bytes */
492 /*----------------------------- ia64 ---------------------------------*/
494 #elif defined (__ia64__) && (defined (linux) || defined (__hpux__))
496 #define USE_GCC_UNWINDER
497 /* Use _Unwind_Backtrace driven exceptions on ia64 HP-UX and ia64
498 GNU/Linux, where _Unwind_Backtrace is provided by the system unwind
499 library. On HP-UX 11.23 this requires patch PHSS_33352, which adds
500 _Unwind_Backtrace to the system unwind library. */
502 #define PC_ADJUST -4
505 #endif
507 /*---------------------------------------------------------------------*
508 *-- The post GCC 3.3 infrastructure based implementation --*
509 *---------------------------------------------------------------------*/
511 #if defined (USE_GCC_UNWINDER) && (__GNUC__ * 10 + __GNUC_MINOR__ > 33)
513 /* Conditioning the inclusion on the GCC version is useful to avoid bootstrap
514 path problems, since the included file refers to post 3.3 functions in
515 libgcc, and the stage1 compiler is unlikely to be linked against a post 3.3
516 library. It actually disables the support for backtraces in this compiler
517 for targets defining USE_GCC_UNWINDER, which is OK since we don't use the
518 traceback capability in the compiler anyway.
520 The condition is expressed the way above because we cannot reliably rely on
521 any other macro from the base compiler when compiling stage1. */
523 #include "tb-gcc.c"
525 /*------------------------------------------------------------------*
526 *-- The generic implementation based on frame layout assumptions --*
527 *------------------------------------------------------------------*/
529 #elif defined (USE_GENERIC_UNWINDER)
531 #ifndef CURRENT_STACK_FRAME
532 # define CURRENT_STACK_FRAME ({ char __csf; &__csf; })
533 #endif
535 #ifndef VALID_STACK_FRAME
536 #define VALID_STACK_FRAME(ptr) 1
537 #endif
539 #ifndef MAX
540 #define MAX(x,y) ((x) > (y) ? (x) : (y))
541 #endif
543 #ifndef FORCE_CALL
544 #define FORCE_CALL 0
545 #endif
547 /* Make sure the function is not inlined. */
548 static void forced_callee (void) __attribute__ ((noinline));
550 static void forced_callee (void)
552 /* Make sure the function is not pure. */
553 volatile int i __attribute__ ((unused)) = 0;
557 __gnat_backtrace (void **array,
558 int size,
559 void *exclude_min,
560 void *exclude_max,
561 int skip_frames)
563 struct layout *current;
564 void *top_frame;
565 void *top_stack ATTRIBUTE_UNUSED;
566 int cnt = 0;
568 if (FORCE_CALL)
569 forced_callee ();
571 /* Force a call to builtin_frame_address with a positive argument
572 if required. This is necessary e.g. on SPARC to have the register
573 windows flushed before we attempt to access them on the stack. */
574 #if defined (FETCH_UP_FRAME_ADDRESS) && (FRAME_LEVEL == 0)
575 __builtin_frame_address (1);
576 #endif
578 top_frame = __builtin_frame_address (FRAME_LEVEL);
579 top_stack = CURRENT_STACK_FRAME;
580 current = (struct layout *) ((size_t) top_frame + FRAME_OFFSET (0));
582 /* Skip the number of calls we have been requested to skip, accounting for
583 the BASE_SKIP parameter.
585 FRAME_LEVEL is meaningless for the count adjustment. It impacts where we
586 start retrieving data from, but how many frames "up" we start at is in
587 BASE_SKIP by definition. */
589 skip_frames = MAX (0, skip_frames - BASE_SKIP);
591 while (cnt < skip_frames)
593 current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
594 cnt++;
597 cnt = 0;
598 while (cnt < size)
600 if (STOP_FRAME (current, top_stack) ||
601 !VALID_STACK_FRAME(((char *) current->return_address) + PC_ADJUST))
602 break;
604 if (current->return_address < exclude_min
605 || current->return_address > exclude_max)
606 array[cnt++] = ((char *) current->return_address) + PC_ADJUST;
608 current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
611 return cnt;
614 #else
616 /* No target specific implementation and neither USE_GCC_UNWINDER nor
617 USE_GENERIC_UNWINDER defined. */
619 /*------------------------------*
620 *-- The dummy implementation --*
621 *------------------------------*/
624 __gnat_backtrace (void **array ATTRIBUTE_UNUSED,
625 int size ATTRIBUTE_UNUSED,
626 void *exclude_min ATTRIBUTE_UNUSED,
627 void *exclude_max ATTRIBUTE_UNUSED,
628 int skip_frames ATTRIBUTE_UNUSED)
630 return 0;
633 #endif
635 #endif
637 #ifdef __cplusplus
639 #endif