1 /****************************************************************************
3 * GNAT RUN-TIME COMPONENTS *
7 * C Implementation File *
9 * Copyright (C) 2000-2018, Free Software Foundation, Inc. *
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. *
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. *
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/>. *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
30 ****************************************************************************/
32 /* This file contains low level support for stack unwinding using GCC intrinsic
34 It has been tested on the following configurations:
53 #ifdef __alpha_vxworks
64 /* We don't want fancy_abort here. */
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__)
102 #define IS_BAD_PTR(ptr) (IsBadCodePtr((FARPROC)ptr))
105 __gnat_backtrace (void **array
,
112 UNWIND_HISTORY_TABLE history
;
115 /* Get the context. */
116 RtlCaptureContext (&context
);
118 /* Setup unwind history table (a cached to speed-up unwinding). */
119 memset (&history
, 0, sizeof (history
));
124 PRUNTIME_FUNCTION RuntimeFunction
;
125 KNONVOLATILE_CONTEXT_POINTERS NvContext
;
128 ULONG64 EstablisherFrame
;
130 /* Get function metadata. */
131 RuntimeFunction
= RtlLookupFunctionEntry
132 (context
.Rip
, &ImageBase
, &history
);
134 if (!RuntimeFunction
)
136 /* In case of failure, assume this is a leaf function. */
137 context
.Rip
= *(ULONG64
*) context
.Rsp
;
142 /* If the last unwinding step failed somehow, stop here. */
143 if (IS_BAD_PTR(context
.Rip
))
147 memset (&NvContext
, 0, sizeof (KNONVOLATILE_CONTEXT_POINTERS
));
148 RtlVirtualUnwind (0, ImageBase
, context
.Rip
, RuntimeFunction
,
149 &context
, &HandlerData
, &EstablisherFrame
,
153 /* 0 means bottom of the stack. */
154 if (context
.Rip
== 0)
163 /* Excluded frames. */
164 if ((void *)context
.Rip
>= exclude_min
165 && (void *)context
.Rip
<= exclude_max
)
168 array
[i
++] = (void *)(context
.Rip
- 2);
176 /* No target specific implementation. */
178 /*----------------------------------------------------------------*
179 *-- Target specific definitions for the generic implementation --*
180 *----------------------------------------------------------------*/
182 /* The stack layout is specified by the target ABI. The "generic" scheme is
183 based on the following assumption:
185 The stack layout from some frame pointer is such that the information
186 required to compute the backtrace is available at static offsets.
188 For a given frame, the information we are interested in is the saved return
189 address (somewhere after the call instruction in the caller) and a pointer
190 to the caller's frame. The former is the base of the call chain information
191 we store in the tracebacks array. The latter allows us to loop over the
192 successive frames in the chain.
194 To initiate the process, we retrieve an initial frame address using the
195 appropriate GCC builtin (__builtin_frame_address).
197 This scheme is unfortunately not applicable on every target because the
198 stack layout is not necessarily regular (static) enough. On targets where
199 this scheme applies, the implementation relies on the following items:
201 o struct layout, describing the expected stack data layout relevant to the
202 information we are interested in,
204 o FRAME_OFFSET, the offset, from a given frame address or frame pointer
205 value, at which this layout will be found,
207 o FRAME_LEVEL, controls how many frames up we get at to start with,
208 from the initial frame pointer we compute by way of the GCC builtin,
210 0 is most often the appropriate value. 1 may be necessary on targets
211 where return addresses are saved by a function in it's caller's frame
214 o PC_ADJUST, to account for the difference between a call point (address
215 of a call instruction), which is what we want in the output array, and
216 the associated return address, which is what we retrieve from the stack.
218 o STOP_FRAME, to decide whether we reached the top of the call chain, and
219 thus if the process shall stop.
225 | | | (FRAME_OFFSET) |
226 | | | : | (PC_ADJUST)
227 | | layout:| return_address ----------------+
229 +--------------- next_frame | |
232 | +----------------+ | +-----+
233 | | : |<- Base fp | | : |
234 | | (FRAME_OFFSET) | (FRAME_LEVEL) | | : |
236 | layout:| return_address --------------------> | [0]
237 | | ... | (PC_ADJUST) +-----+
238 +---------- next_frame | traceback[]
245 Since we inherently deal with return addresses, there is an implicit shift
246 by at least one for the initial point we are able to observe in the chain.
248 On some targets (e.g. sparc-solaris), the first return address we can
249 easily get without special code is even our caller's return address, so
250 there is a initial shift of two.
252 BASE_SKIP represents this initial shift, which is the minimal "skip_frames"
253 value we support. We could add special code for the skip_frames < BASE_SKIP
254 cases. This is not done currently because there is virtually no situation
255 in which this would be useful.
257 Finally, to account for some ABI specificities, a target may (but does
260 o FORCE_CALL, to force a call to a dummy function at the very beginning
261 of the computation. See the PPC AIX target for an example where this
264 o FETCH_UP_FRAME, to force an invocation of __builtin_frame_address with a
265 positive argument right after a possibly forced call even if FRAME_LEVEL
266 is 0. See the SPARC Solaris case for an example where this is useful.
270 /*------------------- Darwin 8 (OSX 10.4) or newer ----------------------*/
271 #if defined (__APPLE__) \
272 && defined (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) \
273 && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1040
275 #define USE_GCC_UNWINDER
277 #if defined (__i386__) || defined (__x86_64__)
279 #elif defined (__ppc__) || defined (__ppc64__)
281 #elif defined (__arm__)
283 #elif defined (__arm64__)
286 #error Unhandled darwin architecture.
289 /*---------------------------- x86 *BSD --------------------------------*/
291 #elif defined (__i386__) && \
292 ( defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__) )
294 #define USE_GCC_UNWINDER
295 /* The generic unwinder is not used for this target because the default
296 implementation doesn't unwind on the BSD platforms. AMD64 targets use the
297 gcc unwinder for all platforms, so let's keep i386 consistent with that.
301 /* The minimum size of call instructions on this architecture is 2 bytes */
303 /*---------------------- ARM VxWorks ------------------------------------*/
304 #elif (defined (ARMEL) && defined (__vxworks))
309 #define USE_GCC_UNWINDER
312 #if ((_WRS_VXWORKS_MAJOR >= 7) && (_VX_CPU != ARMARCH8A))
313 #define USING_ARM_UNWINDING 1
316 /*---------------------- PPC AIX/PPC Lynx 178/Older Darwin --------------*/
317 #elif ((defined (_POWER) && defined (_AIX)) || \
318 (defined (__powerpc__) && defined (__Lynx__) && !defined(__ELF__)) || \
319 (defined (__ppc__) && defined (__APPLE__)))
321 #define USE_GENERIC_UNWINDER
327 void *return_address
;
330 #define FRAME_OFFSET(FP) 0
333 /* Eventhough the base PPC ABI states that a toplevel frame entry
334 should to feature a null backchain, AIX might expose a null return
337 /* Then LynxOS-178 features yet another variation, with return_address
338 == &<entrypoint>, with two possible entry points (one for the main
339 process and one for threads). Beware that &bla returns the address
340 of a descriptor when "bla" is a function. Getting the code address
341 requires an extra dereference. */
343 #if defined (__Lynx__)
344 extern void __start(); /* process entry point. */
345 extern void __runnit(); /* thread entry point. */
346 #define EXTRA_STOP_CONDITION(CURRENT) \
347 ((CURRENT)->return_address == *(void**)&__start \
348 || (CURRENT)->return_address == *(void**)&__runnit)
350 #define EXTRA_STOP_CONDITION(CURRENT) (0)
353 #define STOP_FRAME(CURRENT, TOP_STACK) \
354 (((void *) (CURRENT) < (TOP_STACK)) \
355 || (CURRENT)->return_address == NULL \
356 || EXTRA_STOP_CONDITION(CURRENT))
358 /* The PPC ABI has an interesting specificity: the return address saved by a
359 function is located in it's caller's frame, and the save operation only
360 takes place if the function performs a call.
362 To have __gnat_backtrace retrieve its own return address, we then
366 #define FRAME_LEVEL 1
370 /*----------- PPC ELF (GNU/Linux & VxWorks & Lynx178e) -------------------*/
372 #elif (defined (_ARCH_PPC) && defined (__vxworks)) || \
373 (defined (__powerpc__) && defined (__Lynx__) && defined(__ELF__)) || \
374 (defined (__linux__) && defined (__powerpc__))
376 #if defined (_ARCH_PPC64) && !defined (__USING_SJLJ_EXCEPTIONS__)
377 #define USE_GCC_UNWINDER
379 #define USE_GENERIC_UNWINDER
385 void *return_address
;
389 #define FRAME_LEVEL 1
390 /* See the PPC AIX case for an explanation of these values. */
392 #define FRAME_OFFSET(FP) 0
395 /* According to the base PPC ABI, a toplevel frame entry should feature
396 a null backchain. What happens at signal handler frontiers isn't so
397 well specified, so we add a safety guard on top. */
399 #define STOP_FRAME(CURRENT, TOP_STACK) \
400 ((CURRENT)->next == 0 || ((long)(CURRENT)->next % __alignof__(void*)) != 0)
404 /*-------------------------- SPARC Solaris -----------------------------*/
406 #elif defined (__sun__) && defined (__sparc__)
408 #define USE_GENERIC_UNWINDER
410 /* These definitions are inspired from the Appendix D (Software
411 Considerations) of the SPARC V8 architecture manual. */
416 void *return_address
;
420 #define STACK_BIAS 2047 /* V9 ABI */
422 #define STACK_BIAS 0 /* V8 ABI */
425 #define FRAME_LEVEL 0
426 #define FRAME_OFFSET(FP) (14 * sizeof (void*) + (FP ? STACK_BIAS : 0))
428 #define STOP_FRAME(CURRENT, TOP_STACK) \
429 ((CURRENT)->return_address == 0|| (CURRENT)->next == 0 \
430 || (void *) (CURRENT) < (TOP_STACK))
432 /* The SPARC register windows need to be flushed before we may access them
433 from the stack. This is achieved by way of builtin_frame_address only
434 when the "count" argument is positive, so force at least one such call. */
435 #define FETCH_UP_FRAME_ADDRESS
438 /* From the frame pointer of frame N, we are accessing the flushed register
439 window of frame N-1 (positive offset from fp), in which we retrieve the
440 saved return address. We then end up with our caller's return address. */
442 /*---------------------------- x86 & x86_64 ---------------------------------*/
444 #elif defined (__i386__) || defined (__x86_64__)
446 #if defined (__WIN32)
448 #define IS_BAD_PTR(ptr) (IsBadCodePtr((FARPROC)ptr))
449 #elif defined (__sun__)
450 #define IS_BAD_PTR(ptr) ((unsigned long)ptr == -1UL)
452 #define IS_BAD_PTR(ptr) 0
455 /* Use the dwarf2 unwinder when we expect to have dwarf2 tables at
456 hand. Backtraces will reliably stop on frames missing such tables,
457 but our only alternative is the generic unwinder which requires
458 compilation forcing a frame pointer to be reliable. */
460 #if (defined (__x86_64__) || defined (__linux__)) && !defined (__USING_SJLJ_EXCEPTIONS__)
461 #define USE_GCC_UNWINDER
463 #define USE_GENERIC_UNWINDER
469 void *return_address
;
472 #define FRAME_LEVEL 1
473 /* builtin_frame_address (1) is expected to work on this family of targets,
474 and (0) might return the soft stack pointer, which does not designate a
475 location where a backchain and a return address might be found. */
477 #define FRAME_OFFSET(FP) 0
479 #define STOP_FRAME(CURRENT, TOP_STACK) \
480 (IS_BAD_PTR((long)(CURRENT)) \
481 || IS_BAD_PTR((long)(CURRENT)->return_address) \
482 || (CURRENT)->return_address == 0 \
483 || (void *) ((CURRENT)->next) < (TOP_STACK) \
484 || (void *) (CURRENT) < (TOP_STACK))
486 #define BASE_SKIP (1+FRAME_LEVEL)
488 /* On i386 architecture we check that at the call point we really have a call
489 insn. Possible call instructions are:
491 call addr16 E8 xx xx xx xx
493 call off(reg) FF xx xx
494 lcall addr seg 9A xx xx xx xx xx xx
496 This check will not catch all cases but it will increase the backtrace
497 reliability on this architecture.
500 #define VALID_STACK_FRAME(ptr) \
502 && (((*((ptr) - 3) & 0xff) == 0xe8) \
503 || ((*((ptr) - 5) & 0xff) == 0x9a) \
504 || ((*((ptr) - 1) & 0xff) == 0xff) \
505 || (((*(ptr) & 0xd0ff) == 0xd0ff))))
507 /*----------------------------- qnx ----------------------------------*/
509 #elif defined (__QNX__)
511 #define USE_GCC_UNWINDER
513 #if defined (__aarch64__)
516 #error Unhandled QNX architecture.
519 /*----------------------------- ia64 ---------------------------------*/
521 #elif defined (__ia64__) && (defined (__linux__) || defined (__hpux__))
523 #define USE_GCC_UNWINDER
524 /* Use _Unwind_Backtrace driven exceptions on ia64 HP-UX and ia64
525 GNU/Linux, where _Unwind_Backtrace is provided by the system unwind
526 library. On HP-UX 11.23 this requires patch PHSS_33352, which adds
527 _Unwind_Backtrace to the system unwind library. */
534 /*---------------------------------------------------------------------*
535 *-- The post GCC 3.3 infrastructure based implementation --*
536 *---------------------------------------------------------------------*/
538 #if defined (USE_GCC_UNWINDER) && (__GNUC__ * 10 + __GNUC_MINOR__ > 33)
540 /* Conditioning the inclusion on the GCC version is useful to avoid bootstrap
541 path problems, since the included file refers to post 3.3 functions in
542 libgcc, and the stage1 compiler is unlikely to be linked against a post 3.3
543 library. It actually disables the support for backtraces in this compiler
544 for targets defining USE_GCC_UNWINDER, which is OK since we don't use the
545 traceback capability in the compiler anyway.
547 The condition is expressed the way above because we cannot reliably rely on
548 any other macro from the base compiler when compiling stage1. */
550 #ifdef USING_ARM_UNWINDING
551 /* This value is not part of the enumerated reason codes defined in unwind.h
552 for ARM style unwinding, but is used in the included "C" code, so we
553 define it to a reasonable value to avoid a compilation error. */
554 #define _URC_NORMAL_STOP 0
558 /*------------------------------------------------------------------*
559 *-- The generic implementation based on frame layout assumptions --*
560 *------------------------------------------------------------------*/
562 #elif defined (USE_GENERIC_UNWINDER)
564 #ifndef CURRENT_STACK_FRAME
565 # define CURRENT_STACK_FRAME ({ char __csf; &__csf; })
568 #ifndef VALID_STACK_FRAME
569 #define VALID_STACK_FRAME(ptr) 1
573 #define MAX(x,y) ((x) > (y) ? (x) : (y))
580 /* Make sure the function is not inlined. */
581 static void forced_callee (void) __attribute__ ((noinline
));
583 static void forced_callee (void)
585 /* Make sure the function is not pure. */
586 volatile int i
__attribute__ ((unused
)) = 0;
590 __gnat_backtrace (void **array
,
596 struct layout
*current
;
598 void *top_stack ATTRIBUTE_UNUSED
;
604 /* Force a call to builtin_frame_address with a positive argument
605 if required. This is necessary e.g. on SPARC to have the register
606 windows flushed before we attempt to access them on the stack. */
607 #if defined (FETCH_UP_FRAME_ADDRESS) && (FRAME_LEVEL == 0)
608 __builtin_frame_address (1);
611 top_frame
= __builtin_frame_address (FRAME_LEVEL
);
612 top_stack
= CURRENT_STACK_FRAME
;
613 current
= (struct layout
*) ((size_t) top_frame
+ FRAME_OFFSET (0));
615 /* Skip the number of calls we have been requested to skip, accounting for
616 the BASE_SKIP parameter.
618 FRAME_LEVEL is meaningless for the count adjustment. It impacts where we
619 start retrieving data from, but how many frames "up" we start at is in
620 BASE_SKIP by definition. */
622 skip_frames
= MAX (0, skip_frames
- BASE_SKIP
);
624 while (cnt
< skip_frames
)
626 current
= (struct layout
*) ((size_t) current
->next
+ FRAME_OFFSET (1));
633 if (STOP_FRAME (current
, top_stack
) ||
634 !VALID_STACK_FRAME(((char *) current
->return_address
) + PC_ADJUST
))
637 if (current
->return_address
< exclude_min
638 || current
->return_address
> exclude_max
)
639 array
[cnt
++] = ((char *) current
->return_address
) + PC_ADJUST
;
641 current
= (struct layout
*) ((size_t) current
->next
+ FRAME_OFFSET (1));
649 /* No target specific implementation and neither USE_GCC_UNWINDER nor
650 USE_GENERIC_UNWINDER defined. */
652 /*------------------------------*
653 *-- The dummy implementation --*
654 *------------------------------*/
657 __gnat_backtrace (void **array ATTRIBUTE_UNUSED
,
658 int size ATTRIBUTE_UNUSED
,
659 void *exclude_min ATTRIBUTE_UNUSED
,
660 void *exclude_max ATTRIBUTE_UNUSED
,
661 int skip_frames ATTRIBUTE_UNUSED
)