PR rtl-optimization/57003
[official-gcc.git] / gcc / ada / tracebak.c
blob54ec90f674b96d7561f3b16d7f10770554807751
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-2014, 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 (_WIN64) && defined (__SEH__)
100 #include <windows.h>
103 __gnat_backtrace (void **array,
104 int size,
105 void *exclude_min,
106 void *exclude_max,
107 int skip_frames)
109 CONTEXT context;
110 UNWIND_HISTORY_TABLE history;
111 int i;
113 /* Get the context. */
114 RtlCaptureContext (&context);
116 /* Setup unwind history table (a cached to speed-up unwinding). */
117 memset (&history, 0, sizeof (history));
119 i = 0;
120 while (1)
122 PRUNTIME_FUNCTION RuntimeFunction;
123 KNONVOLATILE_CONTEXT_POINTERS NvContext;
124 ULONG64 ImageBase;
125 VOID *HandlerData;
126 ULONG64 EstablisherFrame;
128 /* Get function metadata. */
129 RuntimeFunction = RtlLookupFunctionEntry
130 (context.Rip, &ImageBase, &history);
132 if (!RuntimeFunction)
134 /* In case of failure, assume this is a leaf function. */
135 context.Rip = *(ULONG64 *) context.Rsp;
136 context.Rsp += 8;
138 else
140 /* Unwind. */
141 memset (&NvContext, 0, sizeof (KNONVOLATILE_CONTEXT_POINTERS));
142 RtlVirtualUnwind (0, ImageBase, context.Rip, RuntimeFunction,
143 &context, &HandlerData, &EstablisherFrame,
144 &NvContext);
147 /* 0 means bottom of the stack. */
148 if (context.Rip == 0)
149 break;
151 /* Skip frames. */
152 if (skip_frames > 1)
154 skip_frames--;
155 continue;
157 /* Excluded frames. */
158 if ((void *)context.Rip >= exclude_min
159 && (void *)context.Rip <= exclude_max)
160 continue;
162 array[i++] = (void *)(context.Rip - 2);
163 if (i >= size)
164 break;
166 return i;
168 #else
170 /* No target specific implementation. */
172 /*----------------------------------------------------------------*
173 *-- Target specific definitions for the generic implementation --*
174 *----------------------------------------------------------------*/
176 /* The stack layout is specified by the target ABI. The "generic" scheme is
177 based on the following assumption:
179 The stack layout from some frame pointer is such that the information
180 required to compute the backtrace is available at static offsets.
182 For a given frame, the information we are interested in is the saved return
183 address (somewhere after the call instruction in the caller) and a pointer
184 to the caller's frame. The former is the base of the call chain information
185 we store in the tracebacks array. The latter allows us to loop over the
186 successive frames in the chain.
188 To initiate the process, we retrieve an initial frame address using the
189 appropriate GCC builtin (__builtin_frame_address).
191 This scheme is unfortunately not applicable on every target because the
192 stack layout is not necessarily regular (static) enough. On targets where
193 this scheme applies, the implementation relies on the following items:
195 o struct layout, describing the expected stack data layout relevant to the
196 information we are interested in,
198 o FRAME_OFFSET, the offset, from a given frame address or frame pointer
199 value, at which this layout will be found,
201 o FRAME_LEVEL, controls how many frames up we get at to start with,
202 from the initial frame pointer we compute by way of the GCC builtin,
204 0 is most often the appropriate value. 1 may be necessary on targets
205 where return addresses are saved by a function in it's caller's frame
206 (e.g. PPC).
208 o PC_ADJUST, to account for the difference between a call point (address
209 of a call instruction), which is what we want in the output array, and
210 the associated return address, which is what we retrieve from the stack.
212 o STOP_FRAME, to decide whether we reached the top of the call chain, and
213 thus if the process shall stop.
216 : stack
217 | +----------------+
218 | +-------->| : |
219 | | | (FRAME_OFFSET) |
220 | | | : | (PC_ADJUST)
221 | | layout:| return_address ----------------+
222 | | | .... | |
223 +--------------- next_frame | |
224 | | .... | |
225 | | | |
226 | +----------------+ | +-----+
227 | | : |<- Base fp | | : |
228 | | (FRAME_OFFSET) | (FRAME_LEVEL) | | : |
229 | | : | +---> | [1]
230 | layout:| return_address --------------------> | [0]
231 | | ... | (PC_ADJUST) +-----+
232 +---------- next_frame | traceback[]
233 | ... |
235 +----------------+
237 o BASE_SKIP,
239 Since we inherently deal with return addresses, there is an implicit shift
240 by at least one for the initial point we are able to observe in the chain.
242 On some targets (e.g. sparc-solaris), the first return address we can
243 easily get without special code is even our caller's return address, so
244 there is a initial shift of two.
246 BASE_SKIP represents this initial shift, which is the minimal "skip_frames"
247 value we support. We could add special code for the skip_frames < BASE_SKIP
248 cases. This is not done currently because there is virtually no situation
249 in which this would be useful.
251 Finally, to account for some ABI specificities, a target may (but does
252 not have to) define:
254 o FORCE_CALL, to force a call to a dummy function at the very beginning
255 of the computation. See the PPC AIX target for an example where this
256 is useful.
258 o FETCH_UP_FRAME, to force an invocation of __builtin_frame_address with a
259 positive argument right after a possibly forced call even if FRAME_LEVEL
260 is 0. See the SPARC Solaris case for an example where this is useful.
264 /*------------------- Darwin 8 (OSX 10.4) or newer ----------------------*/
265 #if defined (__APPLE__) \
266 && defined (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) \
267 && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1040
269 #define USE_GCC_UNWINDER
271 #if defined (__i386__) || defined (__x86_64__)
272 #define PC_ADJUST -2
273 #elif defined (__ppc__) || defined (__ppc64__)
274 #define PC_ADJUST -4
275 #else
276 #error Unhandled darwin architecture.
277 #endif
279 /*---------------------- PPC AIX/PPC Lynx 178/Older Darwin ------------------*/
280 #elif ((defined (_POWER) && defined (_AIX)) || \
281 (defined (__powerpc__) && defined (__Lynx__) && !defined(__ELF__)) || \
282 (defined (__ppc__) && defined (__APPLE__)))
284 #define USE_GENERIC_UNWINDER
286 struct layout
288 struct layout *next;
289 void *pad;
290 void *return_address;
293 #define FRAME_OFFSET(FP) 0
294 #define PC_ADJUST -4
296 /* Eventhough the base PPC ABI states that a toplevel frame entry
297 should to feature a null backchain, AIX might expose a null return
298 address instead. */
300 /* Then LynxOS-178 features yet another variation, with return_address
301 == &<entrypoint>, with two possible entry points (one for the main
302 process and one for threads). Beware that &bla returns the address
303 of a descriptor when "bla" is a function. Getting the code address
304 requires an extra dereference. */
306 #if defined (__Lynx__)
307 extern void __start(); /* process entry point. */
308 extern void __runnit(); /* thread entry point. */
309 #define EXTRA_STOP_CONDITION(CURRENT) \
310 ((CURRENT)->return_address == *(void**)&__start \
311 || (CURRENT)->return_address == *(void**)&__runnit)
312 #else
313 #define EXTRA_STOP_CONDITION(CURRENT) (0)
314 #endif
316 #define STOP_FRAME(CURRENT, TOP_STACK) \
317 (((void *) (CURRENT) < (TOP_STACK)) \
318 || (CURRENT)->return_address == NULL \
319 || EXTRA_STOP_CONDITION(CURRENT))
321 /* The PPC ABI has an interesting specificity: the return address saved by a
322 function is located in it's caller's frame, and the save operation only
323 takes place if the function performs a call.
325 To have __gnat_backtrace retrieve its own return address, we then
326 define ... */
328 #define FORCE_CALL 1
329 #define FRAME_LEVEL 1
331 #define BASE_SKIP 1
333 /*-------------------- PPC ELF (GNU/Linux & VxWorks) ---------------------*/
335 #elif (defined (_ARCH_PPC) && defined (__vxworks)) || \
336 (defined (linux) && defined (__powerpc__))
338 #define USE_GENERIC_UNWINDER
340 struct layout
342 struct layout *next;
343 void *return_address;
346 #define FORCE_CALL 1
347 #define FRAME_LEVEL 1
348 /* See the PPC AIX case for an explanation of these values. */
350 #define FRAME_OFFSET(FP) 0
351 #define PC_ADJUST -4
353 /* According to the base PPC ABI, a toplevel frame entry should feature
354 a null backchain. What happens at signal handler frontiers isn't so
355 well specified, so we add a safety guard on top. */
357 #define STOP_FRAME(CURRENT, TOP_STACK) \
358 ((CURRENT)->next == 0 || ((long)(CURRENT)->next % __alignof__(void*)) != 0)
360 #define BASE_SKIP 1
362 /*-------------------------- SPARC Solaris -----------------------------*/
364 #elif defined (sun) && defined (sparc)
366 #define USE_GENERIC_UNWINDER
368 /* These definitions are inspired from the Appendix D (Software
369 Considerations) of the SPARC V8 architecture manual. */
371 struct layout
373 struct layout *next;
374 void *return_address;
377 #ifdef __arch64__
378 #define STACK_BIAS 2047 /* V9 ABI */
379 #else
380 #define STACK_BIAS 0 /* V8 ABI */
381 #endif
383 #define FRAME_LEVEL 0
384 #define FRAME_OFFSET(FP) (14 * sizeof (void*) + (FP ? STACK_BIAS : 0))
385 #define PC_ADJUST 0
386 #define STOP_FRAME(CURRENT, TOP_STACK) \
387 ((CURRENT)->return_address == 0|| (CURRENT)->next == 0 \
388 || (void *) (CURRENT) < (TOP_STACK))
390 /* The SPARC register windows need to be flushed before we may access them
391 from the stack. This is achieved by way of builtin_frame_address only
392 when the "count" argument is positive, so force at least one such call. */
393 #define FETCH_UP_FRAME_ADDRESS
395 #define BASE_SKIP 2
396 /* From the frame pointer of frame N, we are accessing the flushed register
397 window of frame N-1 (positive offset from fp), in which we retrieve the
398 saved return address. We then end up with our caller's return address. */
400 /*------------------------------- x86 ----------------------------------*/
402 #elif defined (i386)
404 #if defined (__WIN32)
405 #include <windows.h>
406 #define IS_BAD_PTR(ptr) (IsBadCodePtr((FARPROC)ptr))
407 #elif defined (sun)
408 #define IS_BAD_PTR(ptr) ((unsigned long)ptr == -1UL)
409 #else
410 #define IS_BAD_PTR(ptr) 0
411 #endif
413 /* Starting with GCC 4.6, -fomit-frame-pointer is turned on by default for
414 32-bit x86/Linux as well and DWARF 2 unwind tables are emitted instead.
415 See the x86-64 case below for the drawbacks with this approach. */
416 #if defined (linux) && (__GNUC__ * 10 + __GNUC_MINOR__ > 45)
417 #define USE_GCC_UNWINDER
418 #else
419 #define USE_GENERIC_UNWINDER
420 #endif
422 struct layout
424 struct layout *next;
425 void *return_address;
428 #define FRAME_LEVEL 1
429 /* builtin_frame_address (1) is expected to work on this target, and (0) might
430 return the soft stack pointer, which does not designate a location where a
431 backchain and a return address might be found. */
433 #define FRAME_OFFSET(FP) 0
434 #define PC_ADJUST -2
435 #define STOP_FRAME(CURRENT, TOP_STACK) \
436 (IS_BAD_PTR((long)(CURRENT)) \
437 || IS_BAD_PTR((long)(CURRENT)->return_address) \
438 || (CURRENT)->return_address == 0 \
439 || (void *) ((CURRENT)->next) < (TOP_STACK) \
440 || (void *) (CURRENT) < (TOP_STACK))
442 #define BASE_SKIP (1+FRAME_LEVEL)
444 /* On i386 architecture we check that at the call point we really have a call
445 insn. Possible call instructions are:
447 call addr16 E8 xx xx xx xx
448 call reg FF Dx
449 call off(reg) FF xx xx
450 lcall addr seg 9A xx xx xx xx xx xx
452 This check will not catch all cases but it will increase the backtrace
453 reliability on this architecture.
456 #define VALID_STACK_FRAME(ptr) \
457 (!IS_BAD_PTR(ptr) \
458 && (((*((ptr) - 3) & 0xff) == 0xe8) \
459 || ((*((ptr) - 5) & 0xff) == 0x9a) \
460 || ((*((ptr) - 1) & 0xff) == 0xff) \
461 || (((*(ptr) & 0xd0ff) == 0xd0ff))))
463 /*----------------------------- x86_64 ---------------------------------*/
465 #elif defined (__x86_64__)
467 #define USE_GCC_UNWINDER
468 /* The generic unwinder is not used for this target because it is based
469 on frame layout assumptions that are not reliable on this target (the
470 rbp register is very likely used for something else than storing the
471 frame pointer in optimized code). Hence, we use the GCC unwinder
472 based on DWARF 2 call frame information, although it has the drawback
473 of not being able to unwind through frames compiled without DWARF 2
474 information.
477 #define PC_ADJUST -2
478 /* The minimum size of call instructions on this architecture is 2 bytes */
480 /*----------------------------- ia64 ---------------------------------*/
482 #elif defined (__ia64__) && (defined (linux) || defined (__hpux__))
484 #define USE_GCC_UNWINDER
485 /* Use _Unwind_Backtrace driven exceptions on ia64 HP-UX and ia64
486 GNU/Linux, where _Unwind_Backtrace is provided by the system unwind
487 library. On HP-UX 11.23 this requires patch PHSS_33352, which adds
488 _Unwind_Backtrace to the system unwind library. */
490 #define PC_ADJUST -4
493 #endif
495 /*---------------------------------------------------------------------*
496 *-- The post GCC 3.3 infrastructure based implementation --*
497 *---------------------------------------------------------------------*/
499 #if defined (USE_GCC_UNWINDER) && (__GNUC__ * 10 + __GNUC_MINOR__ > 33)
501 /* Conditioning the inclusion on the GCC version is useful to avoid bootstrap
502 path problems, since the included file refers to post 3.3 functions in
503 libgcc, and the stage1 compiler is unlikely to be linked against a post 3.3
504 library. It actually disables the support for backtraces in this compiler
505 for targets defining USE_GCC_UNWINDER, which is OK since we don't use the
506 traceback capability in the compiler anyway.
508 The condition is expressed the way above because we cannot reliably rely on
509 any other macro from the base compiler when compiling stage1. */
511 #include "tb-gcc.c"
513 /*------------------------------------------------------------------*
514 *-- The generic implementation based on frame layout assumptions --*
515 *------------------------------------------------------------------*/
517 #elif defined (USE_GENERIC_UNWINDER)
519 #ifndef CURRENT_STACK_FRAME
520 # define CURRENT_STACK_FRAME ({ char __csf; &__csf; })
521 #endif
523 #ifndef VALID_STACK_FRAME
524 #define VALID_STACK_FRAME(ptr) 1
525 #endif
527 #ifndef MAX
528 #define MAX(x,y) ((x) > (y) ? (x) : (y))
529 #endif
531 #ifndef FORCE_CALL
532 #define FORCE_CALL 0
533 #endif
535 /* Make sure the function is not inlined. */
536 static void forced_callee (void) __attribute__ ((noinline));
538 static void forced_callee (void)
540 /* Make sure the function is not pure. */
541 volatile int i __attribute__ ((unused)) = 0;
545 __gnat_backtrace (void **array,
546 int size,
547 void *exclude_min,
548 void *exclude_max,
549 int skip_frames)
551 struct layout *current;
552 void *top_frame;
553 void *top_stack ATTRIBUTE_UNUSED;
554 int cnt = 0;
556 if (FORCE_CALL)
557 forced_callee ();
559 /* Force a call to builtin_frame_address with a positive argument
560 if required. This is necessary e.g. on SPARC to have the register
561 windows flushed before we attempt to access them on the stack. */
562 #if defined (FETCH_UP_FRAME_ADDRESS) && (FRAME_LEVEL == 0)
563 __builtin_frame_address (1);
564 #endif
566 top_frame = __builtin_frame_address (FRAME_LEVEL);
567 top_stack = CURRENT_STACK_FRAME;
568 current = (struct layout *) ((size_t) top_frame + FRAME_OFFSET (0));
570 /* Skip the number of calls we have been requested to skip, accounting for
571 the BASE_SKIP parameter.
573 FRAME_LEVEL is meaningless for the count adjustment. It impacts where we
574 start retrieving data from, but how many frames "up" we start at is in
575 BASE_SKIP by definition. */
577 skip_frames = MAX (0, skip_frames - BASE_SKIP);
579 while (cnt < skip_frames)
581 current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
582 cnt++;
585 cnt = 0;
586 while (cnt < size)
588 if (STOP_FRAME (current, top_stack) ||
589 !VALID_STACK_FRAME(((char *) current->return_address) + PC_ADJUST))
590 break;
592 if (current->return_address < exclude_min
593 || current->return_address > exclude_max)
594 array[cnt++] = ((char *) current->return_address) + PC_ADJUST;
596 current = (struct layout *) ((size_t) current->next + FRAME_OFFSET (1));
599 return cnt;
602 #else
604 /* No target specific implementation and neither USE_GCC_UNWINDER nor
605 USE_GENERIC_UNWINDER defined. */
607 /*------------------------------*
608 *-- The dummy implementation --*
609 *------------------------------*/
612 __gnat_backtrace (void **array ATTRIBUTE_UNUSED,
613 int size ATTRIBUTE_UNUSED,
614 void *exclude_min ATTRIBUTE_UNUSED,
615 void *exclude_max ATTRIBUTE_UNUSED,
616 int skip_frames ATTRIBUTE_UNUSED)
618 return 0;
621 #endif
623 #endif
625 #ifdef __cplusplus
627 #endif