Add a debug counter for late-combine
[official-gcc.git] / gcc / ada / raise-gcc.c
blob7179f62529e1b87bd75306a1c7b89970518df0b0
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * R A I S E - G C C *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2024, 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 /* Code related to the integration of the GCC mechanism for exception
33 handling. */
35 #ifndef IN_RTS
36 /* For gnat1/gnatbind compilation: use host headers. */
37 # include "config.h"
38 # include "system.h"
39 /* Don't use fancy_abort. */
40 # undef abort
41 #else
42 # if !defined(CERT) && !defined(STANDALONE)
43 # include "tconfig.h"
44 # include "tsystem.h"
45 # else
46 # include "runtime.h"
47 # define HAVE_GETIPINFO 1
48 # endif
49 #endif
51 #ifdef __cplusplus
52 # include <cstdarg>
53 # include <cstddef>
54 # include <cstdlib>
55 #else
56 # include <stdarg.h>
57 # include <stdbool.h>
58 # include <stddef.h>
59 # include <stdlib.h>
60 #endif
62 #include "raise.h"
64 #ifdef __APPLE__
65 /* On MacOS X, versions older than 10.5 don't export _Unwind_GetIPInfo. */
66 #undef HAVE_GETIPINFO
67 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
68 #define HAVE_GETIPINFO 1
69 #endif
70 #endif
72 #if defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
73 /* HP-UX B.11.31 ia64 libunwind doesn't have _Unwind_GetIPInfo. */
74 #undef HAVE_GETIPINFO
75 #define _UA_END_OF_STACK 0
76 #endif
78 /* The names of a couple of "standard" routines for unwinding/propagation
79 actually vary depending on the underlying GCC scheme for exception handling
80 (SJLJ or DWARF). We need a consistently named interface to import from
81 a-except, so wrappers are defined here. */
83 #if defined (__CYGWIN__) || (defined(__SEH__) && defined(STANDALONE))
84 /* Prevent compile error due to unwind-generic.h including <windows.h>,
85 see comment above #include <windows.h> in mingw32.h. */
86 #include "mingw32.h"
87 #endif
89 #ifndef IN_RTS
90 /* For gnat1/gnatbind compilation: cannot use unwind.h, as it is for the
91 target. So mimic configure...
92 This is a hack ???, the real fix is to link gnat1/gnatbind with the
93 runtime of the build compiler. */
94 # ifdef EH_MECHANISM_arm
95 # include "config/arm/unwind-arm.h"
96 # else
97 # include "unwind-generic.h"
98 # endif
99 #else
100 # include "unwind.h"
101 #endif
103 #ifdef __cplusplus
104 extern "C" {
105 #endif
107 typedef struct _Unwind_Context _Unwind_Context;
108 typedef struct _Unwind_Exception _Unwind_Exception;
110 _Unwind_Reason_Code
111 __gnat_Unwind_RaiseException (_Unwind_Exception *);
113 _Unwind_Reason_Code
114 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *, _Unwind_Stop_Fn, void *);
116 extern struct Exception_Occurrence *
117 __gnat_setup_current_excep (_Unwind_Exception *, _Unwind_Action);
119 extern void __gnat_unhandled_except_handler (_Unwind_Exception *);
121 #ifdef CERT
122 /* Called in case of error during propagation. */
123 extern void __gnat_raise_abort (void) __attribute__ ((noreturn));
124 #define abort() __gnat_raise_abort()
126 #elif defined(STANDALONE)
127 #define inhibit_libc
128 #endif
130 #include "unwind-pe.h"
132 #ifdef __ARM_EABI_UNWINDER__
133 /* for memcmp */
134 #include <string.h>
135 #endif
137 /* The known and handled exception classes. */
139 #ifdef __ARM_EABI_UNWINDER__
140 #define CXX_EXCEPTION_CLASS "GNUCC++"
141 #define GNAT_EXCEPTION_CLASS "GNU-Ada"
142 #else
143 #define CXX_EXCEPTION_CLASS 0x474e5543432b2b00ULL
144 #define GNAT_EXCEPTION_CLASS 0x474e552d41646100ULL
145 #endif
147 /* Structure of a C++ exception, represented as a C structure... See
148 unwind-cxx.h for the full definition. */
150 struct __cxa_exception
152 void *exceptionType;
153 void (*exceptionDestructor)(void *);
155 void (*unexpectedHandler)();
156 void (*terminateHandler)();
158 struct __cxa_exception *nextException;
160 int handlerCount;
162 #ifdef __ARM_EABI_UNWINDER__
163 struct __cxa_exception* nextPropagatingException;
165 int propagationCount;
166 #else
167 int handlerSwitchValue;
168 const unsigned char *actionRecord;
169 const unsigned char *languageSpecificData;
170 _Unwind_Ptr catchTemp;
171 void *adjustedPtr;
172 #endif
174 _Unwind_Exception unwindHeader;
177 /* --------------------------------------------------------------
178 -- The DB stuff below is there for debugging purposes only. --
179 -------------------------------------------------------------- */
181 #ifndef inhibit_libc
183 #define DB_PHASES 0x1
184 #define DB_CSITE 0x2
185 #define DB_ACTIONS 0x4
186 #define DB_REGIONS 0x8
188 #define DB_ERR 0x1000
190 /* The "action" stuff below is also there for debugging purposes only. */
192 typedef struct
194 _Unwind_Action phase;
195 const char * description;
196 } phase_descriptor;
198 static const phase_descriptor phase_descriptors[]
199 = {{ _UA_SEARCH_PHASE, "SEARCH_PHASE" },
200 { _UA_CLEANUP_PHASE, "CLEANUP_PHASE" },
201 { _UA_HANDLER_FRAME, "HANDLER_FRAME" },
202 { _UA_FORCE_UNWIND, "FORCE_UNWIND" },
203 { -1, 0}};
205 static int
206 db_accepted_codes (void)
208 static int accepted_codes = -1;
210 if (accepted_codes == -1)
212 char * db_env = (char *) getenv ("EH_DEBUG");
214 accepted_codes = db_env ? (atoi (db_env) | DB_ERR) : 0;
215 /* Arranged for ERR stuff to always be visible when the variable
216 is defined. One may just set the variable to 0 to see the ERR
217 stuff only. */
220 return accepted_codes;
223 #define DB_INDENT_INCREASE 0x01
224 #define DB_INDENT_DECREASE 0x02
225 #define DB_INDENT_OUTPUT 0x04
226 #define DB_INDENT_NEWLINE 0x08
227 #define DB_INDENT_RESET 0x10
229 #define DB_INDENT_UNIT 8
231 static void
232 db_indent (int requests)
234 static int current_indentation_level = 0;
236 if (requests & DB_INDENT_RESET)
237 current_indentation_level = 0;
239 if (requests & DB_INDENT_INCREASE)
240 current_indentation_level ++;
242 if (requests & DB_INDENT_DECREASE)
243 current_indentation_level --;
245 if (requests & DB_INDENT_NEWLINE)
246 fprintf (stderr, "\n");
248 if (requests & DB_INDENT_OUTPUT)
249 fprintf (stderr, "%*s", current_indentation_level * DB_INDENT_UNIT, " ");
252 static void ATTRIBUTE_PRINTF_2
253 db (int db_code, const char * msg_format, ...)
255 if (db_accepted_codes () & db_code)
257 va_list msg_args;
259 db_indent (DB_INDENT_OUTPUT);
261 va_start (msg_args, msg_format);
262 vfprintf (stderr, msg_format, msg_args);
263 va_end (msg_args);
267 static void
268 db_phases (int phases)
270 const phase_descriptor *a = phase_descriptors;
272 if (! (db_accepted_codes () & DB_PHASES))
273 return;
275 db (DB_PHASES, "\n");
277 for (; a->description != 0; a++)
278 if (phases & a->phase)
279 db (DB_PHASES, "%s ", a->description);
281 db (DB_PHASES, " :\n");
283 #else /* !inhibit_libc */
284 #define db_phases(X)
285 #define db_indent(X)
286 #define db(X, ...)
287 #endif /* !inhibit_libc */
289 /* ---------------------------------------------------------------
290 -- Now come a set of useful structures and helper routines. --
291 --------------------------------------------------------------- */
293 /* There are three major runtime tables involved, generated by the
294 GCC back-end. Contents slightly vary depending on the underlying
295 implementation scheme (dwarf zero cost / sjlj).
297 =======================================
298 * Tables for the dwarf zero cost case *
299 =======================================
301 They are fully documented in:
302 http://sourcery.mentor.com/public/cxx-abi/exceptions.pdf
303 Here is a shorter presentation, with some specific comments for Ada.
305 call_site []
306 -------------------------------------------------------------------
307 * region-start | region-length | landing-pad | first-action-index *
308 -------------------------------------------------------------------
310 Identify possible actions to be taken and where to resume control
311 for that when an exception propagates through a pc inside the region
312 delimited by start and length.
314 A null landing-pad indicates that nothing is to be done.
316 Otherwise, first-action-index provides an entry into the action[]
317 table which heads a list of possible actions to be taken (see below).
319 If it is determined that indeed an action should be taken, that
320 is, if one action filter matches the exception being propagated,
321 then control should be transferred to landing-pad.
323 A null first-action-index indicates that there are only cleanups
324 to run there.
326 action []
327 -------------------------------
328 * action-filter | next-action *
329 -------------------------------
331 This table contains lists (called action chains) of possible actions
332 associated with call-site entries described in the call-site [] table.
333 There is at most one action list per call-site entry. It is SLEB128
334 encoded.
336 A null action-filter indicates a cleanup.
338 Non null action-filters provide an index into the ttypes [] table
339 (see below), from which information may be retrieved to check if it
340 matches the exception being propagated.
342 * action-filter > 0:
343 means there is a regular handler to be run The value is also passed
344 to the landing pad to dispatch the exception.
346 * action-filter < 0:
347 means there is a some "exception_specification" data to retrieve,
348 which is only relevant for C++ and should never show up for Ada.
349 (Exception specification specifies which exceptions can be thrown
350 by a function. Such filter is emitted around the body of C++
351 functions defined like:
352 void foo ([...]) throw (A, B) { [...] }
353 These can be viewed as negativ filter: the landing pad is branched
354 to for exceptions that doesn't match the filter and usually aborts
355 the program).
357 * next-action
358 points to the next entry in the list using a relative byte offset. 0
359 indicates there is no other entry.
361 ttypes []
362 ---------------
363 * ttype-value *
364 ---------------
366 This table is an array of addresses.
368 A null value indicates a catch-all handler. (Not used by Ada)
370 Non null values are used to match the exception being propagated:
371 In C++ this is a pointer to some rtti data, while in Ada this is an
372 exception id (with a fake id for others).
374 For C++, this table is actually also used to store "exception
375 specification" data. The differentiation between the two kinds
376 of entries is made by the sign of the associated action filter,
377 which translates into positive or negative offsets from the
378 so called base of the table:
380 Exception Specification data is stored at positive offsets from
381 the ttypes table base, which Exception Type data is stored at
382 negative offsets:
384 ---------------------------------------------------------------------------
386 Here is a quick summary of the tables organization:
388 +-- Unwind_Context (pc, ...)
390 |(pc)
392 | CALL-SITE[]
394 | +=============================================================+
395 | | region-start + length | landing-pad | first-action-index |
396 | +=============================================================+
397 +-> | pc range 0 => no-action 0 => cleanups only |
398 | !0 => jump @ N --+ |
399 +====================================================== | ====+
402 ACTION [] |
404 +==========================================================+ |
405 | action-filter | next-action | |
406 +==========================================================+ |
407 | 0 => cleanup | |
408 | >0 => ttype index for handler ------+ 0 => end of chain | <-+
409 | <0 => ttype index for spec data | |
410 +==================================== | ===================+
413 TTYPES [] |
414 | Offset negated from
415 +=====================+ | the actual base.
416 | ttype-value | |
417 +============+=====================+ |
418 | | ... | |
419 | ... | exception id | <---+
420 | | ... |
421 | handlers +---------------------+
422 | | ... |
423 | ... | ... |
424 | | ... |
425 +============+=====================+ <<------ Table base
426 | ... | ... |
427 | specs | ... | (should not see negative filter
428 | ... | ... | values for Ada).
429 +============+=====================+
432 ============================
433 * Tables for the sjlj case *
434 ============================
436 So called "function contexts" are pushed on a context stack by calls to
437 _Unwind_SjLj_Register on function entry, and popped off at exit points by
438 calls to _Unwind_SjLj_Unregister. The current call_site for a function is
439 updated in the function context as the function's code runs along.
441 The generic unwinding engine in _Unwind_RaiseException walks the function
442 context stack and not the actual call chain.
444 The ACTION and TTYPES tables remain unchanged, which allows to search them
445 during the propagation phase to determine whether or not the propagated
446 exception is handled somewhere. When it is, we only "jump" up once directly
447 to the context where the handler will be found. Besides, this allows "break
448 exception unhandled" to work also
450 The CALL-SITE table is setup differently, though: the pc attached to the
451 unwind context is a direct index into the table, so the entries in this
452 table do not hold region bounds any more.
454 A special index (-1) is used to indicate that no action is possibly
455 connected with the context at hand, so null landing pads cannot appear
456 in the table.
458 Additionally, landing pad values in the table do not represent code address
459 to jump at, but so called "dispatch" indices used by a common landing pad
460 for the function to switch to the appropriate post-landing-pad.
462 +-- Unwind_Context (pc, ...)
464 | pc = call-site index
465 | 0 => terminate (should not see this for Ada)
466 | -1 => no-action
468 | CALL-SITE[]
470 | +=====================================+
471 | | landing-pad | first-action-index |
472 | +=====================================+
473 +-> | 0 => cleanups only |
474 | dispatch index N |
475 +=====================================+
478 ===================================
479 * Basic organization of this unit *
480 ===================================
482 The major point of this unit is to provide an exception propagation
483 personality routine for Ada. This is __gnat_personality_v0.
485 It is provided with a pointer to the propagated exception, an unwind
486 context describing a location the propagation is going through, and a
487 couple of other arguments including a description of the current
488 propagation phase.
490 It shall return to the generic propagation engine what is to be performed
491 next, after possible context adjustments, depending on what it finds in the
492 traversed context (a handler for the exception, a cleanup, nothing, ...),
493 and on the propagation phase.
495 A number of structures and subroutines are used for this purpose, as
496 sketched below:
498 o region_descriptor: General data associated with the context (base pc,
499 call-site table, action table, ttypes table, ...)
501 o action_descriptor: Data describing the action to be taken for the
502 propagated exception in the provided context (kind of action: nothing,
503 handler, cleanup; pointer to the action table entry, ...).
505 raise
507 ... (a-except.adb)
509 Propagate_Exception (a-exexpr.adb)
512 _Unwind_RaiseException (libgcc)
514 | (Ada frame)
516 +--> __gnat_personality_v0 (context, exception)
518 +--> get_region_description_for (context)
520 +--> get_action_description_for (ip, exception, region)
522 | +--> get_call_site_action_for (context, region)
523 | (one version for each underlying scheme)
525 +--> setup_to_install (context)
527 This unit is inspired from the C++ version found in eh_personality.cc,
528 part of libstdc++-v3.
533 /* This is an incomplete "proxy" of the structure of exception objects as
534 built by the GNAT runtime library. Accesses to other fields than the common
535 header are performed through subprogram calls to alleviate the need of an
536 exact counterpart here and potential alignment/size issues for the common
537 header. See a-exexpr.adb. */
539 typedef struct
541 _Unwind_Exception common;
542 /* ABI header, maximally aligned. */
543 } _GNAT_Exception;
545 /* The three constants below are specific ttype identifiers for special
546 exception ids. Their type should match what a-exexpr exports. */
548 extern char __gnat_others_value;
549 #define GNAT_OTHERS ((Exception_Id) &__gnat_others_value)
551 extern char __gnat_all_others_value;
552 #define GNAT_ALL_OTHERS ((Exception_Id) &__gnat_all_others_value)
554 extern char __gnat_unhandled_others_value;
555 #define GNAT_UNHANDLED_OTHERS ((Exception_Id) &__gnat_unhandled_others_value)
557 /* Describe the useful region data associated with an unwind context. */
559 typedef struct
561 /* The base pc of the region. */
562 _Unwind_Ptr base;
564 /* Pointer to the Language Specific Data for the region. */
565 _Unwind_Ptr lsda;
567 /* Call-Site data associated with this region. */
568 unsigned char call_site_encoding;
569 const unsigned char *call_site_table;
571 /* The base to which are relative landing pad offsets inside the call-site
572 entries . */
573 _Unwind_Ptr lp_base;
575 /* Action-Table associated with this region. */
576 const unsigned char *action_table;
578 /* Ttype data associated with this region. */
579 unsigned char ttype_encoding;
580 const unsigned char *ttype_table;
581 _Unwind_Ptr ttype_base;
583 } region_descriptor;
585 /* Extract and adjust the IP (instruction pointer) from an exception
586 context. */
588 static _Unwind_Ptr
589 get_ip_from_context (_Unwind_Context *uw_context)
591 int ip_before_insn = 0;
592 #ifdef HAVE_GETIPINFO
593 _Unwind_Ptr ip = _Unwind_GetIPInfo (uw_context, &ip_before_insn);
594 #else
595 _Unwind_Ptr ip = _Unwind_GetIP (uw_context);
596 #endif
598 #if !defined(__USING_SJLJ_EXCEPTIONS__) && defined(__CHERI__)
599 #if __has_builtin (__builtin_code_address_from_pointer)
600 ip = __builtin_code_address_from_pointer ((void *)ip);
601 #elif defined(__aarch64__)
602 /* Clang doesn't have __builtin_code_address_from_pointer to abstract over
603 target-specific differences. On AArch64, we need to drop the LSB of the
604 instruction pointer because it's not part of the address; it indicates the
605 CPU mode. */
606 ip &= ~1UL;
607 #endif
608 #endif
610 /* Subtract 1 if necessary because GetIPInfo yields a call return address
611 in this case, while we are interested in information for the call point.
612 This does not always yield the exact call instruction address but always
613 brings the IP back within the corresponding region. */
614 if (!ip_before_insn)
615 ip--;
617 return ip;
620 static void
621 db_region_for (region_descriptor *region, _Unwind_Ptr ip)
623 #ifndef inhibit_libc
624 if (! (db_accepted_codes () & DB_REGIONS))
625 return;
627 db (DB_REGIONS, "For ip @ %p => ", (void *)ip);
629 if (region->lsda)
630 db (DB_REGIONS, "lsda @ %p", (void *)region->lsda);
631 else
632 db (DB_REGIONS, "no lsda");
634 db (DB_REGIONS, "\n");
635 #endif
638 /* Retrieve the ttype entry associated with FILTER in the REGION's
639 ttype table. */
641 static _Unwind_Ptr
642 get_ttype_entry_for (region_descriptor *region, long filter)
644 _Unwind_Ptr ttype_entry;
646 filter *= size_of_encoded_value (region->ttype_encoding);
647 read_encoded_value_with_base
648 (region->ttype_encoding, region->ttype_base,
649 region->ttype_table - filter, &ttype_entry);
651 return ttype_entry;
654 /* Fill out the REGION descriptor for the provided UW_CONTEXT. */
656 static void
657 get_region_description_for (_Unwind_Context *uw_context,
658 region_descriptor *region)
660 const unsigned char * p;
661 _uleb128_t tmp;
662 unsigned char lpbase_encoding;
664 /* Get the base address of the lsda information. If the provided context
665 is null or if there is no associated language specific data, there's
666 nothing we can/should do. */
667 region->lsda
668 = (_Unwind_Ptr) (uw_context
669 ? _Unwind_GetLanguageSpecificData (uw_context) : 0);
671 if (! region->lsda)
672 return;
674 /* Parse the lsda and fill the region descriptor. */
675 p = (const unsigned char *)region->lsda;
677 region->base = _Unwind_GetRegionStart (uw_context);
679 /* Find @LPStart, the base to which landing pad offsets are relative. */
680 lpbase_encoding = *p++;
681 if (lpbase_encoding != DW_EH_PE_omit)
682 p = read_encoded_value
683 (uw_context, lpbase_encoding, p, &region->lp_base);
684 else
685 region->lp_base = region->base;
687 /* Find @TType, the base of the handler and exception spec type data. */
688 region->ttype_encoding = *p++;
689 if (region->ttype_encoding != DW_EH_PE_omit)
691 p = read_uleb128 (p, &tmp);
692 region->ttype_table = p + tmp;
694 else
695 region->ttype_table = 0;
697 region->ttype_base
698 = base_of_encoded_value (region->ttype_encoding, uw_context);
700 /* Get the encoding and length of the call-site table; the action table
701 immediately follows. */
702 region->call_site_encoding = *p++;
703 region->call_site_table = read_uleb128 (p, &tmp);
705 region->action_table = region->call_site_table + tmp;
709 /* Describe an action to be taken when propagating an exception up to
710 some context. */
712 enum action_kind
714 /* Found some call site base data, but need to analyze further
715 before being able to decide. */
716 unknown,
718 /* There is nothing relevant in the context at hand. */
719 nothing,
721 /* There are only cleanups to run in this context. */
722 cleanup,
724 /* There is a handler for the exception in this context. */
725 handler,
727 /* There is a handler for the exception, but it is only for catching
728 unhandled exceptions. */
729 unhandler
732 /* filter value for cleanup actions. */
733 static const int cleanup_filter = 0;
735 typedef struct
737 /* The kind of action to be taken. */
738 enum action_kind kind;
740 /* A pointer to the action record entry. */
741 const unsigned char *table_entry;
743 /* Where we should jump to actually take an action (trigger a cleanup or an
744 exception handler). */
745 _Unwind_Ptr landing_pad;
747 /* If we have a handler matching our exception, these are the filter to
748 trigger it and the corresponding id. */
749 _Unwind_Sword ttype_filter;
751 } action_descriptor;
753 static void
754 db_action_for (action_descriptor *action, _Unwind_Ptr ip)
756 #ifndef inhibit_libc
757 db (DB_ACTIONS, "For ip @ %p => ", (void *)ip);
759 switch (action->kind)
761 case unknown:
762 db (DB_ACTIONS, "lpad @ %p, record @ %p\n",
763 (void *) action->landing_pad, action->table_entry);
764 break;
766 case nothing:
767 db (DB_ACTIONS, "Nothing\n");
768 break;
770 case cleanup:
771 db (DB_ACTIONS, "Cleanup\n");
772 break;
774 case handler:
775 db (DB_ACTIONS, "Handler, filter = %d\n", (int) action->ttype_filter);
776 break;
778 default:
779 db (DB_ACTIONS, "Err? Unexpected action kind !\n");
780 break;
782 #endif
785 /* Search the call_site_table of REGION for an entry appropriate for the
786 UW_CONTEXT's IP. If one is found, store the associated landing_pad
787 and action_table entry, and set the ACTION kind to unknown for further
788 analysis. Otherwise, set the ACTION kind to nothing.
790 There are two variants of this routine, depending on the underlying
791 mechanism (DWARF/SJLJ), which account for differences in the tables. */
793 #ifdef __USING_SJLJ_EXCEPTIONS__
795 #define __builtin_eh_return_data_regno(x) x
797 static void
798 get_call_site_action_for (_Unwind_Ptr call_site,
799 region_descriptor *region,
800 action_descriptor *action)
802 /* call_site is a direct index into the call-site table, with two special
803 values : -1 for no-action and 0 for "terminate". The latter should never
804 show up for Ada. To test for the former, beware that _Unwind_Ptr might
805 be unsigned. */
807 if ((int)call_site < 0)
809 action->kind = nothing;
811 else if (call_site == 0)
813 db (DB_ERR, "========> Err, null call_site for Ada/sjlj\n");
814 action->kind = nothing;
816 else
818 _uleb128_t cs_lp, cs_action;
819 const unsigned char *p;
821 /* Let the caller know there may be an action to take, but let it
822 determine the kind. */
823 action->kind = unknown;
825 /* We have a direct index into the call-site table, but this table is
826 made of leb128 values, the encoding length of which is variable. We
827 can't merely compute an offset from the index, then, but have to read
828 all the entries before the one of interest. */
829 p = region->call_site_table;
832 p = read_uleb128 (p, &cs_lp);
833 p = read_uleb128 (p, &cs_action);
835 while (--call_site);
837 action->landing_pad = cs_lp + 1;
839 if (cs_action)
840 action->table_entry = region->action_table + cs_action - 1;
841 else
842 action->table_entry = 0;
846 #else /* !__USING_SJLJ_EXCEPTIONS__ */
848 static void
849 get_call_site_action_for (_Unwind_Ptr ip,
850 region_descriptor *region,
851 action_descriptor *action)
853 const unsigned char *p = region->call_site_table;
855 /* Unless we are able to determine otherwise... */
856 action->kind = nothing;
858 db (DB_CSITE, "\n");
860 while (p < region->action_table)
862 _Unwind_Ptr cs_start, cs_len, cs_lp;
863 _uleb128_t cs_action;
865 /* Note that all call-site encodings are "absolute" displacements. */
866 p = read_encoded_value (0, region->call_site_encoding, p, &cs_start);
867 p = read_encoded_value (0, region->call_site_encoding, p, &cs_len);
868 #ifdef __CHERI_PURE_CAPABILITY__
869 // Single uleb128 value as the capability marker.
870 _Unwind_Ptr marker = 0;
871 p = read_encoded_value (0, DW_EH_PE_uleb128, p, &marker);
872 if (marker == 0xd)
874 /* 8-byte offset to the (indirected) capability. */
875 p = read_encoded_value (0, DW_EH_PE_pcrel | DW_EH_PE_udata8, p,
876 &cs_lp);
878 else if (marker)
880 /* Unsupported landing pad marker value. */
881 abort ();
883 else
884 cs_lp = 0; // No landing pad.
885 #else
886 p = read_encoded_value (0, region->call_site_encoding, p, &cs_lp);
887 #endif
889 p = read_uleb128 (p, &cs_action);
891 db (DB_CSITE,
892 "c_site @ %p (+%p), len = %p, lpad @ %p (+%p)\n",
893 (char *)region->base + cs_start, (void *)cs_start, (void *)cs_len,
894 (char *)region->lp_base + cs_lp, (void *)cs_lp);
896 /* The table is sorted, so if we've passed the IP, stop. */
897 if (ip < region->base + (size_t)cs_start)
898 break;
900 /* If we have a match, fill the ACTION fields accordingly. */
901 else if (ip < region->base + (size_t)cs_start + (size_t)cs_len)
903 /* Let the caller know there may be an action to take, but let it
904 determine the kind. */
905 action->kind = unknown;
907 if (cs_lp)
909 #ifdef __CHERI_PURE_CAPABILITY__
910 action->landing_pad = *(_Unwind_Ptr *)cs_lp;
911 #else
912 action->landing_pad = region->lp_base + cs_lp;
913 #endif
915 else
916 action->landing_pad = 0;
918 if (cs_action)
919 action->table_entry = region->action_table + cs_action - 1;
920 else
921 action->table_entry = 0;
923 db (DB_CSITE, "+++\n");
924 return;
928 db (DB_CSITE, "---\n");
931 #endif /* __USING_SJLJ_EXCEPTIONS__ */
933 /* With CHOICE an exception choice representing an "exception - when"
934 argument, and PROPAGATED_EXCEPTION a pointer to the currently propagated
935 occurrence, return true if the latter matches the former, that is, if
936 PROPAGATED_EXCEPTION is caught by the handling code controlled by CHOICE.
939 #define Is_Handled_By_Others __gnat_is_handled_by_others
940 #define Language_For __gnat_language_for
941 #define Foreign_Data_For __gnat_foreign_data_for
942 #define EID_For __gnat_eid_for
944 extern bool Is_Handled_By_Others (Exception_Id eid);
945 extern char Language_For (Exception_Id eid);
946 extern void *Foreign_Data_For (Exception_Id eid);
947 extern Exception_Id EID_For (_GNAT_Exception *e);
949 #define Foreign_Exception system__exceptions__foreign_exception
950 extern struct Exception_Data Foreign_Exception;
952 /* Return true iff the exception class of EXCEPT is EC. */
954 static int
955 exception_class_eq (const _GNAT_Exception *except,
956 const _Unwind_Exception_Class ec)
958 #ifdef __ARM_EABI_UNWINDER__
959 return memcmp (except->common.exception_class, ec, 8) == 0;
960 #else
961 return except->common.exception_class == ec;
962 #endif
965 /* Return how CHOICE matches PROPAGATED_EXCEPTION. */
967 static enum action_kind
968 is_handled_by (Exception_Id choice, _GNAT_Exception *propagated_exception)
970 /* All others choice match everything. */
971 if (choice == GNAT_ALL_OTHERS)
972 return handler;
974 /* GNAT exception occurrence. */
975 if (exception_class_eq (propagated_exception, GNAT_EXCEPTION_CLASS))
977 if (choice == GNAT_UNHANDLED_OTHERS)
978 return unhandler;
980 Exception_Id E = EID_For (propagated_exception);
982 /* Base matching rules: An exception data (id) matches itself, "when
983 all_others" matches anything and "when others" matches anything
984 unless explicitly stated otherwise in the propagated occurrence. */
985 if (choice == E || (choice == GNAT_OTHERS && Is_Handled_By_Others (E)))
986 return handler;
988 /* Otherwise, it doesn't match an Ada choice. */
989 return nothing;
992 /* All others and others choice match any foreign exception. */
993 if (choice == GNAT_ALL_OTHERS
994 || choice == GNAT_OTHERS
995 #ifndef CERT
996 || choice == &Foreign_Exception
997 #endif
999 return handler;
1001 #ifndef CERT
1002 /* C++ exception occurrences. */
1003 if (exception_class_eq (propagated_exception, CXX_EXCEPTION_CLASS)
1004 && Language_For (choice) == 'C')
1006 void *choice_typeinfo = Foreign_Data_For (choice);
1007 void *except_typeinfo =
1008 (((struct __cxa_exception *)
1009 ((_Unwind_Exception *)propagated_exception + 1)) - 1)
1010 ->exceptionType;
1012 /* Typeinfo are directly compared, which might not be correct if they
1013 aren't merged. ??? We should call the == operator if this module is
1014 compiled in C++. */
1015 if (choice_typeinfo == except_typeinfo)
1016 return handler;
1018 #endif
1020 return nothing;
1023 /* Fill out the ACTION to be taken from propagating UW_EXCEPTION up to
1024 UW_CONTEXT in REGION. */
1026 static void
1027 get_action_description_for (_Unwind_Ptr ip,
1028 _Unwind_Exception *uw_exception,
1029 _Unwind_Action uw_phase,
1030 region_descriptor *region,
1031 action_descriptor *action)
1033 _GNAT_Exception *gnat_exception = (_GNAT_Exception *) uw_exception;
1035 /* Search the call site table first, which may get us a landing pad as well
1036 as the head of an action record list. */
1037 get_call_site_action_for (ip, region, action);
1038 db_action_for (action, ip);
1040 /* If there is not even a call_site entry, we are done. */
1041 if (action->kind == nothing)
1042 return;
1044 /* Otherwise, check what we have at the place of the call site. */
1046 /* No landing pad => no cleanups or handlers. */
1047 if (action->landing_pad == 0)
1049 action->kind = nothing;
1050 return;
1053 /* Landing pad + null table entry => only cleanups. */
1054 else if (action->table_entry == 0)
1056 action->kind = cleanup;
1057 action->ttype_filter = cleanup_filter;
1058 /* The filter initialization is not strictly necessary, as cleanup-only
1059 landing pads don't look at the filter value. It is there to ensure
1060 we don't pass random values and so trigger potential confusion when
1061 installing the context later on. */
1062 return;
1065 /* Landing pad + Table entry => handlers + possible cleanups. */
1066 else
1068 const unsigned char * p = action->table_entry;
1069 _sleb128_t ar_filter, ar_disp;
1071 action->kind = nothing;
1073 while (1)
1075 p = read_sleb128 (p, &ar_filter);
1076 read_sleb128 (p, &ar_disp);
1077 /* Don't assign p here, as it will be incremented by ar_disp
1078 below. */
1080 /* Null filters are for cleanups. */
1081 if (ar_filter == cleanup_filter)
1083 action->kind = cleanup;
1084 action->ttype_filter = cleanup_filter;
1085 /* The filter initialization is required here, to ensure
1086 the target landing pad branches to the cleanup code if
1087 we happen not to find a matching handler. */
1090 /* Positive filters are for regular handlers. */
1091 else if (ar_filter > 0)
1093 /* Do not catch an exception if the _UA_FORCE_UNWIND flag is
1094 passed (to follow the ABI). */
1095 if (!(uw_phase & _UA_FORCE_UNWIND))
1097 enum action_kind act;
1099 /* See if the filter we have is for an exception which
1100 matches the one we are propagating. */
1101 Exception_Id choice
1102 = (Exception_Id) get_ttype_entry_for (region, ar_filter);
1104 act = is_handled_by (choice, gnat_exception);
1105 if (act != nothing)
1107 action->kind = act;
1108 action->ttype_filter = ar_filter;
1109 return;
1114 /* Negative filter values are for C++ exception specifications.
1115 Should not be there for Ada :/ */
1116 else
1117 db (DB_ERR, "========> Err, filter < 0 for Ada/dwarf\n");
1119 if (ar_disp == 0)
1120 return;
1122 p += ar_disp;
1127 /* Setup in UW_CONTEXT the eh return target IP and data registers, which will
1128 be restored with the others and retrieved by the landing pad once the jump
1129 occurred. */
1131 static void
1132 setup_to_install (_Unwind_Context *uw_context,
1133 _Unwind_Exception *uw_exception,
1134 _Unwind_Ptr uw_landing_pad,
1135 int uw_filter)
1137 /* 1/ exception object pointer, which might be provided back to
1138 _Unwind_Resume (and thus to this personality routine) if we are jumping
1139 to a cleanup. */
1140 _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (0),
1141 (_Unwind_Word)uw_exception);
1143 /* 2/ handler switch value register, which will also be used by the target
1144 landing pad to decide what action it shall take. */
1145 _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (1),
1146 (_Unwind_Word)uw_filter);
1148 /* Setup the address we should jump at to reach the code where there is the
1149 "something" we found. */
1150 _Unwind_SetIP (uw_context, uw_landing_pad);
1153 /* The following is defined from a-except.adb. Its purpose is to enable
1154 automatic backtraces upon exception raise, as provided through the
1155 GNAT.Traceback facilities. */
1156 extern void __gnat_notify_handled_exception (struct Exception_Occurrence *);
1157 extern void __gnat_notify_unhandled_exception (struct Exception_Occurrence *);
1159 /* Below is the eh personality routine per se. We currently assume that only
1160 GNU-Ada exceptions are met. */
1162 /* By default, the personality routine is public. */
1163 #define PERSONALITY_STORAGE
1165 #ifdef __USING_SJLJ_EXCEPTIONS__
1166 #define PERSONALITY_FUNCTION __gnat_personality_sj0
1167 #elif defined (__SEH__)
1168 #define PERSONALITY_FUNCTION __gnat_personality_imp
1169 /* The public personality routine for seh is __gnat_personality_seh0, defined
1170 below using the SEH convention. This is a wrapper around the GNU routine,
1171 which is static. */
1172 #undef PERSONALITY_STORAGE
1173 #define PERSONALITY_STORAGE static
1174 #else
1175 #define PERSONALITY_FUNCTION __gnat_personality_v0
1176 #endif
1178 #if defined (__ARM_EABI_UNWINDER__) \
1179 && (defined (IN_RTS) || GCC_VERSION > 9000)
1180 #define TARGET_ATTRIBUTE __attribute__((target ("general-regs-only")))
1181 #else
1182 #define TARGET_ATTRIBUTE
1183 #endif
1185 /* Code executed to continue unwinding. With the ARM unwinder, the
1186 personality routine must unwind one frame (per EHABI 7.3 4.). */
1188 static _Unwind_Reason_Code
1189 TARGET_ATTRIBUTE
1190 continue_unwind (struct _Unwind_Exception* ue_header ATTRIBUTE_UNUSED,
1191 struct _Unwind_Context* uw_context ATTRIBUTE_UNUSED)
1193 #ifdef __ARM_EABI_UNWINDER__
1194 if (__gnu_unwind_frame (ue_header, uw_context) != _URC_OK)
1195 return _URC_FAILURE;
1196 #endif
1197 return _URC_CONTINUE_UNWIND;
1200 /* Common code for the body of GNAT personality routine. This code is shared
1201 between all unwinders. */
1203 static _Unwind_Reason_Code
1204 TARGET_ATTRIBUTE
1205 personality_body (_Unwind_Action uw_phases,
1206 _Unwind_Exception *uw_exception,
1207 _Unwind_Context *uw_context)
1209 region_descriptor region;
1210 action_descriptor action;
1211 _Unwind_Ptr ip;
1213 /* Debug traces. */
1214 db_indent (DB_INDENT_RESET);
1215 db_phases (uw_phases);
1216 db_indent (DB_INDENT_INCREASE);
1218 /* Get the region description for the context we were provided with. This
1219 will tell us if there is some lsda, call_site, action and/or ttype data
1220 for the associated ip. */
1221 get_region_description_for (uw_context, &region);
1223 /* No LSDA => no handlers or cleanups => we shall unwind further up. */
1224 if (! region.lsda)
1225 return continue_unwind (uw_exception, uw_context);
1227 /* Get the instruction pointer. */
1228 ip = get_ip_from_context (uw_context);
1229 db_region_for (&region, ip);
1231 /* Search the call-site and action-record tables for the action associated
1232 with this IP. */
1233 get_action_description_for (ip, uw_exception, uw_phases, &region, &action);
1234 db_action_for (&action, ip);
1236 /* Whatever the phase, if there is nothing relevant in this frame,
1237 unwinding should just go on. */
1238 if (action.kind == nothing)
1239 return continue_unwind (uw_exception, uw_context);
1241 /* If we found something in search phase, we should return a code indicating
1242 what to do next depending on what we found. If we only have cleanups
1243 around, we shall try to unwind further up to find a handler, otherwise,
1244 tell we have a handler, which will trigger the second phase. */
1245 if (uw_phases & _UA_SEARCH_PHASE)
1247 if (action.kind == cleanup)
1249 return continue_unwind (uw_exception, uw_context);
1251 else
1253 #ifdef __ARM_EABI_UNWINDER__
1254 /* Though we do not use this field ourselves, initializing
1255 it is required by the ARM EH ABI before a personality
1256 function in phase1 returns _URC_HANDLER_FOUND, so that
1257 any personality function can use it in phase2 to test
1258 whether the handler frame was reached. */
1259 uw_exception->barrier_cache.sp
1260 = _Unwind_GetGR (uw_context, UNWIND_STACK_REG);
1261 #endif
1263 #ifndef CERT
1264 /* Trigger the appropriate notification routines before the second
1265 phase starts, when the stack is still intact. First install what
1266 needs to be installed in the current exception buffer and fetch
1267 the Ada occurrence pointer to use. */
1269 struct Exception_Occurrence *excep
1270 = __gnat_setup_current_excep (uw_exception, uw_phases);
1272 if (action.kind == unhandler)
1273 __gnat_notify_unhandled_exception (excep);
1274 else
1275 __gnat_notify_handled_exception (excep);
1276 #endif
1278 return _URC_HANDLER_FOUND;
1282 /* We found something in cleanup/handler phase, which might be the handler
1283 or a cleanup for a handled occurrence, or a cleanup for an unhandled
1284 occurrence (we are in a FORCED_UNWIND phase in this case). Install the
1285 context to get there. */
1287 setup_to_install
1288 (uw_context, uw_exception, action.landing_pad, action.ttype_filter);
1290 #ifndef CERT
1291 /* Write current exception so that it can be retrieved from Ada. It was
1292 already done during phase 1, but one or several exceptions may have been
1293 raised in cleanup handlers in between. */
1294 __gnat_setup_current_excep (uw_exception, uw_phases);
1295 #endif
1297 return _URC_INSTALL_CONTEXT;
1300 #ifndef __ARM_EABI_UNWINDER__
1301 typedef int version_arg_t;
1302 typedef _Unwind_Action phases_arg_t;
1304 PERSONALITY_STORAGE _Unwind_Reason_Code
1305 PERSONALITY_FUNCTION (version_arg_t, phases_arg_t,
1306 _Unwind_Exception_Class, _Unwind_Exception *,
1307 _Unwind_Context *);
1309 PERSONALITY_STORAGE _Unwind_Reason_Code
1310 PERSONALITY_FUNCTION (version_arg_t version_arg,
1311 phases_arg_t phases_arg,
1312 _Unwind_Exception_Class uw_exception_class
1313 ATTRIBUTE_UNUSED,
1314 _Unwind_Exception *uw_exception,
1315 _Unwind_Context *uw_context)
1317 /* Fetch the version and phases args with their nominal ABI types for later
1318 use. This is a noop everywhere except on ia64-vms when called from the
1319 Condition Handling Facility. */
1320 int uw_version = (int) version_arg;
1321 _Unwind_Action uw_phases = (_Unwind_Action) phases_arg;
1323 /* Check that we're called from the ABI context we expect. */
1324 if (uw_version != 1)
1325 return _URC_FATAL_PHASE1_ERROR;
1327 return personality_body (uw_phases, uw_exception, uw_context);
1330 #else /* __ARM_EABI_UNWINDER__ */
1332 PERSONALITY_STORAGE _Unwind_Reason_Code
1333 PERSONALITY_FUNCTION (_Unwind_State state,
1334 struct _Unwind_Exception* ue_header,
1335 struct _Unwind_Context* uw_context);
1337 PERSONALITY_STORAGE _Unwind_Reason_Code
1338 TARGET_ATTRIBUTE
1339 PERSONALITY_FUNCTION (_Unwind_State state,
1340 struct _Unwind_Exception* uw_exception,
1341 struct _Unwind_Context* uw_context)
1343 _Unwind_Action uw_phases;
1345 switch (state & _US_ACTION_MASK)
1347 case _US_VIRTUAL_UNWIND_FRAME:
1348 /* Phase 1. */
1349 uw_phases = _UA_SEARCH_PHASE;
1350 break;
1352 case _US_UNWIND_FRAME_STARTING:
1353 /* Phase 2, to call a cleanup. */
1354 uw_phases = _UA_CLEANUP_PHASE;
1355 #if 0
1356 /* ??? We don't use UA_HANDLER_FRAME (except to debug). Futhermore,
1357 barrier_cache.sp isn't yet set. */
1358 if (!(state & _US_FORCE_UNWIND)
1359 && (uw_exception->barrier_cache.sp
1360 == _Unwind_GetGR (uw_context, UNWIND_STACK_REG)))
1361 uw_phases |= _UA_HANDLER_FRAME;
1362 #endif
1363 break;
1365 case _US_UNWIND_FRAME_RESUME:
1366 /* Phase 2, called at the return of a cleanup. In the GNU
1367 implementation, there is nothing left to do, so we simply go on. */
1368 return continue_unwind (uw_exception, uw_context);
1370 default:
1371 return _URC_FAILURE;
1373 uw_phases |= (state & _US_FORCE_UNWIND);
1375 /* The dwarf unwinder assumes the context structure holds things like the
1376 function and LSDA pointers. The ARM implementation caches these in
1377 the exception header (UCB). To avoid rewriting everything we make a
1378 virtual scratch register point at the UCB. This is a GNU specific
1379 requirement. */
1380 _Unwind_SetGR (uw_context, UNWIND_POINTER_REG, (_Unwind_Ptr) uw_exception);
1382 return personality_body (uw_phases, uw_exception, uw_context);
1384 #endif /* __ARM_EABI_UNWINDER__ */
1386 /* Callback routine called by Unwind_ForcedUnwind to execute all the cleanup
1387 before exiting the task. */
1389 #ifndef CERT
1390 _Unwind_Reason_Code
1391 __gnat_cleanupunwind_handler (int version ATTRIBUTE_UNUSED,
1392 _Unwind_Action phases,
1393 _Unwind_Exception_Class eclass ATTRIBUTE_UNUSED,
1394 struct _Unwind_Exception *exception,
1395 struct _Unwind_Context *context ATTRIBUTE_UNUSED,
1396 void *arg ATTRIBUTE_UNUSED)
1398 /* Terminate when the end of the stack is reached. */
1399 if ((phases & _UA_END_OF_STACK) != 0
1400 #if defined (__ia64__) && defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
1401 /* Strictely follow the ia64 ABI: when end of stack is reached,
1402 the callback will be called with a NULL stack pointer.
1403 No need for that when using libgcc unwinder. */
1404 || _Unwind_GetGR (context, 12) == 0
1405 #endif
1407 __gnat_unhandled_except_handler (exception);
1409 /* We know there is at least one cleanup further up. Return so that it
1410 is searched and entered, after which Unwind_Resume will be called
1411 and this hook will gain control again. */
1412 return _URC_NO_REASON;
1414 #endif
1416 /* Define the consistently named wrappers imported by Propagate_Exception. */
1418 _Unwind_Reason_Code
1419 __gnat_Unwind_RaiseException (_Unwind_Exception *e)
1421 #ifdef NO_EXCEPTION_PROPAGATION
1422 abort();
1423 #endif
1425 #ifdef __USING_SJLJ_EXCEPTIONS__
1426 return _Unwind_SjLj_RaiseException (e);
1427 #else
1428 return _Unwind_RaiseException (e);
1429 #endif
1432 _Unwind_Reason_Code
1433 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e ATTRIBUTE_UNUSED,
1434 _Unwind_Stop_Fn handler ATTRIBUTE_UNUSED,
1435 void *argument ATTRIBUTE_UNUSED)
1437 #ifdef __USING_SJLJ_EXCEPTIONS__
1439 # if defined (__APPLE__) && defined (__arm__)
1440 /* There is not ForcedUnwind routine in arm-darwin system library. */
1441 return _URC_FATAL_PHASE1_ERROR;
1442 # else
1443 return _Unwind_SjLj_ForcedUnwind (e, handler, argument);
1444 # endif
1446 #else
1447 return _Unwind_ForcedUnwind (e, handler, argument);
1448 #endif
1451 #if defined (__SEH__) && !defined (__USING_SJLJ_EXCEPTIONS__)
1453 #define STATUS_USER_DEFINED (1U << 29)
1455 /* From unwind-seh.c. */
1456 #define GCC_MAGIC (('G' << 16) | ('C' << 8) | 'C')
1457 #define GCC_EXCEPTION(TYPE) \
1458 (STATUS_USER_DEFINED | ((TYPE) << 24) | GCC_MAGIC)
1459 #define STATUS_GCC_THROW GCC_EXCEPTION (0)
1461 struct Exception_Data *
1462 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg);
1464 struct _Unwind_Exception *
1465 __gnat_create_machine_occurrence_from_signal_handler (Exception_Id,
1466 const char *);
1468 /* Unwind opcodes. */
1469 #define UWOP_PUSH_NONVOL 0
1470 #define UWOP_ALLOC_LARGE 1
1471 #define UWOP_ALLOC_SMALL 2
1472 #define UWOP_SET_FPREG 3
1473 #define UWOP_SAVE_NONVOL 4
1474 #define UWOP_SAVE_NONVOL_FAR 5
1475 #define UWOP_SAVE_XMM128 8
1476 #define UWOP_SAVE_XMM128_FAR 9
1477 #define UWOP_PUSH_MACHFRAME 10
1479 /* Modify the IP value saved in the machine frame. This is really a kludge,
1480 that will be removed if we could propagate the Windows exception (and not
1481 the GCC one).
1483 What is very wrong is that the Windows unwinder will try to decode the
1484 instruction at IP, which isn't valid anymore after the adjustment. */
1486 static void
1487 __gnat_adjust_context (unsigned char *unw, ULONG64 rsp)
1489 unsigned int len;
1491 /* Version 1 or 2. */
1492 if (unw[0] != 1 && unw[0] != 2)
1493 return;
1494 /* No flags, no prologue. */
1495 if (unw[1] != 0)
1496 return;
1497 len = unw[2];
1498 /* No frame. */
1499 if (unw[3] != 0)
1500 return;
1501 /* ??? Skip the first 2 undocumented opcodes for version 2. */
1502 if (unw[0] == 2)
1503 unw += 8;
1504 else
1505 unw += 4;
1506 while (len > 0)
1508 /* Offset in prologue = 0. */
1509 if (unw[0] != 0)
1510 return;
1511 switch (unw[1] & 0xf)
1513 case UWOP_ALLOC_LARGE:
1514 /* Expect < 512KB. */
1515 if ((unw[1] & 0xf0) != 0)
1516 return;
1517 rsp += *(unsigned short *)(unw + 2) * 8;
1518 len--;
1519 unw += 2;
1520 break;
1521 case UWOP_SAVE_NONVOL:
1522 case UWOP_SAVE_XMM128:
1523 len--;
1524 unw += 2;
1525 break;
1526 case UWOP_PUSH_MACHFRAME:
1528 ULONG64 *rip;
1529 rip = (ULONG64 *)rsp;
1530 if ((unw[1] & 0xf0) == 0x10)
1531 rip++;
1532 /* Adjust rip. */
1533 (*rip)++;
1535 return;
1536 default:
1537 /* Unexpected. */
1538 return;
1540 unw += 2;
1541 len--;
1545 EXCEPTION_DISPOSITION
1546 __gnat_personality_seh0 (PEXCEPTION_RECORD ms_exc, void *this_frame,
1547 PCONTEXT ms_orig_context,
1548 PDISPATCHER_CONTEXT ms_disp)
1550 /* Possibly transform run-time errors into Ada exceptions. */
1551 if (!(ms_exc->ExceptionCode & STATUS_USER_DEFINED))
1553 struct Exception_Data *exception;
1554 const char *msg;
1555 ULONG64 excpip = (ULONG64) ms_exc->ExceptionAddress;
1557 if (excpip != 0
1558 && excpip >= (ms_disp->ImageBase
1559 + ms_disp->FunctionEntry->BeginAddress)
1560 && excpip < (ms_disp->ImageBase
1561 + ms_disp->FunctionEntry->EndAddress))
1563 /* This is a fault in this function. We need to adjust the return
1564 address before raising the GCC exception. In order to do that,
1565 we need to locate the machine frame that has been pushed onto
1566 the stack in response to the hardware exception, so we will do
1567 a private unwinding from here, i.e. the frame of the personality
1568 routine, up to the frame immediately following the frame of this
1569 function. This frame corresponds to a dummy prologue which is
1570 never actually executed but instead appears before the real entry
1571 point of an interrupt routine and exists only to provide a place
1572 to simulate the push of a machine frame. */
1573 CONTEXT context;
1574 PRUNTIME_FUNCTION mf_func = NULL;
1575 ULONG64 mf_imagebase;
1576 ULONG64 mf_rsp = 0;
1578 /* Get the current context. */
1579 RtlCaptureContext (&context);
1581 while (1)
1583 PRUNTIME_FUNCTION RuntimeFunction;
1584 ULONG64 ImageBase;
1585 VOID *HandlerData;
1586 ULONG64 EstablisherFrame;
1588 /* Get function metadata. */
1589 RuntimeFunction
1590 = RtlLookupFunctionEntry (context.Rip, &ImageBase,
1591 ms_disp->HistoryTable);
1593 /* Stop once we reached the frame of this function. */
1594 if (RuntimeFunction == ms_disp->FunctionEntry)
1595 break;
1597 mf_func = RuntimeFunction;
1598 mf_imagebase = ImageBase;
1599 mf_rsp = context.Rsp;
1601 if (RuntimeFunction)
1603 /* Unwind. */
1604 RtlVirtualUnwind (0, ImageBase, context.Rip, RuntimeFunction,
1605 &context, &HandlerData, &EstablisherFrame,
1606 NULL);
1608 else
1610 /* In case of failure, assume this is a leaf function. */
1611 context.Rip = *(ULONG64 *) context.Rsp;
1612 context.Rsp += 8;
1615 /* 0 means bottom of the stack. */
1616 if (context.Rip == 0)
1618 mf_func = NULL;
1619 break;
1623 /* If we have found the machine frame, adjust the return address. */
1624 if (mf_func != NULL)
1625 __gnat_adjust_context
1626 ((unsigned char *)(mf_imagebase + mf_func->UnwindData), mf_rsp);
1629 exception = __gnat_map_SEH (ms_exc, &msg);
1630 if (exception != NULL)
1632 /* Directly convert the system exception into a GCC one.
1634 This is really breaking the API, but is necessary for stack size
1635 reasons: the normal way is to call Raise_From_Signal_Handler,
1636 which builds the exception and calls _Unwind_RaiseException,
1637 which unwinds the stack and will call this personality routine.
1638 But the Windows unwinder needs about 2KB of stack. */
1639 struct _Unwind_Exception *exc
1640 = __gnat_create_machine_occurrence_from_signal_handler (exception,
1641 msg);
1642 memset (exc->private_, 0, sizeof (exc->private_));
1643 ms_exc->ExceptionCode = STATUS_GCC_THROW;
1644 ms_exc->NumberParameters = 1;
1645 ms_exc->ExceptionInformation[0] = (ULONG_PTR)exc;
1650 return
1651 _GCC_specific_handler (ms_exc, this_frame, ms_orig_context, ms_disp,
1652 PERSONALITY_FUNCTION);
1655 /* Define __gnat_personality_v0 for convenience */
1657 PERSONALITY_STORAGE ATTRIBUTE_UNUSED _Unwind_Reason_Code
1658 __gnat_personality_v0 (version_arg_t version_arg,
1659 phases_arg_t phases_arg,
1660 _Unwind_Exception_Class uw_exception_class,
1661 _Unwind_Exception *uw_exception,
1662 _Unwind_Context *uw_context)
1664 return PERSONALITY_FUNCTION
1665 (version_arg, phases_arg, uw_exception_class, uw_exception, uw_context);
1668 #endif /* SEH */
1670 #if !defined (__USING_SJLJ_EXCEPTIONS__)
1671 /* Size of the _Unwind_Exception structure. This is used by g-cppexc to get
1672 the offset to the C++ object. */
1674 const int __gnat_unwind_exception_size = sizeof (_Unwind_Exception);
1675 #endif
1677 #ifdef __cplusplus
1679 #endif