Skip several gcc.dg/builtin-dynamic-object-size tests on hppa*-*-hpux*
[official-gcc.git] / gcc / ada / raise-gcc.c
blobbdf1c26e612f0b4079fbb97ab5daee91ab055e4e
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-2023, 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 ip = __builtin_code_address_from_pointer ((void *)ip);
600 #endif
602 /* Subtract 1 if necessary because GetIPInfo yields a call return address
603 in this case, while we are interested in information for the call point.
604 This does not always yield the exact call instruction address but always
605 brings the IP back within the corresponding region. */
606 if (!ip_before_insn)
607 ip--;
609 return ip;
612 static void
613 db_region_for (region_descriptor *region, _Unwind_Ptr ip)
615 #ifndef inhibit_libc
616 if (! (db_accepted_codes () & DB_REGIONS))
617 return;
619 db (DB_REGIONS, "For ip @ %p => ", (void *)ip);
621 if (region->lsda)
622 db (DB_REGIONS, "lsda @ %p", (void *)region->lsda);
623 else
624 db (DB_REGIONS, "no lsda");
626 db (DB_REGIONS, "\n");
627 #endif
630 /* Retrieve the ttype entry associated with FILTER in the REGION's
631 ttype table. */
633 static _Unwind_Ptr
634 get_ttype_entry_for (region_descriptor *region, long filter)
636 _Unwind_Ptr ttype_entry;
638 filter *= size_of_encoded_value (region->ttype_encoding);
639 read_encoded_value_with_base
640 (region->ttype_encoding, region->ttype_base,
641 region->ttype_table - filter, &ttype_entry);
643 return ttype_entry;
646 /* Fill out the REGION descriptor for the provided UW_CONTEXT. */
648 static void
649 get_region_description_for (_Unwind_Context *uw_context,
650 region_descriptor *region)
652 const unsigned char * p;
653 _uleb128_t tmp;
654 unsigned char lpbase_encoding;
656 /* Get the base address of the lsda information. If the provided context
657 is null or if there is no associated language specific data, there's
658 nothing we can/should do. */
659 region->lsda
660 = (_Unwind_Ptr) (uw_context
661 ? _Unwind_GetLanguageSpecificData (uw_context) : 0);
663 if (! region->lsda)
664 return;
666 /* Parse the lsda and fill the region descriptor. */
667 p = (const unsigned char *)region->lsda;
669 region->base = _Unwind_GetRegionStart (uw_context);
671 /* Find @LPStart, the base to which landing pad offsets are relative. */
672 lpbase_encoding = *p++;
673 if (lpbase_encoding != DW_EH_PE_omit)
674 p = read_encoded_value
675 (uw_context, lpbase_encoding, p, &region->lp_base);
676 else
677 region->lp_base = region->base;
679 /* Find @TType, the base of the handler and exception spec type data. */
680 region->ttype_encoding = *p++;
681 if (region->ttype_encoding != DW_EH_PE_omit)
683 p = read_uleb128 (p, &tmp);
684 region->ttype_table = p + tmp;
686 else
687 region->ttype_table = 0;
689 region->ttype_base
690 = base_of_encoded_value (region->ttype_encoding, uw_context);
692 /* Get the encoding and length of the call-site table; the action table
693 immediately follows. */
694 region->call_site_encoding = *p++;
695 region->call_site_table = read_uleb128 (p, &tmp);
697 region->action_table = region->call_site_table + tmp;
701 /* Describe an action to be taken when propagating an exception up to
702 some context. */
704 enum action_kind
706 /* Found some call site base data, but need to analyze further
707 before being able to decide. */
708 unknown,
710 /* There is nothing relevant in the context at hand. */
711 nothing,
713 /* There are only cleanups to run in this context. */
714 cleanup,
716 /* There is a handler for the exception in this context. */
717 handler,
719 /* There is a handler for the exception, but it is only for catching
720 unhandled exceptions. */
721 unhandler
724 /* filter value for cleanup actions. */
725 static const int cleanup_filter = 0;
727 typedef struct
729 /* The kind of action to be taken. */
730 enum action_kind kind;
732 /* A pointer to the action record entry. */
733 const unsigned char *table_entry;
735 /* Where we should jump to actually take an action (trigger a cleanup or an
736 exception handler). */
737 _Unwind_Ptr landing_pad;
739 /* If we have a handler matching our exception, these are the filter to
740 trigger it and the corresponding id. */
741 _Unwind_Sword ttype_filter;
743 } action_descriptor;
745 static void
746 db_action_for (action_descriptor *action, _Unwind_Ptr ip)
748 #ifndef inhibit_libc
749 db (DB_ACTIONS, "For ip @ %p => ", (void *)ip);
751 switch (action->kind)
753 case unknown:
754 db (DB_ACTIONS, "lpad @ %p, record @ %p\n",
755 (void *) action->landing_pad, action->table_entry);
756 break;
758 case nothing:
759 db (DB_ACTIONS, "Nothing\n");
760 break;
762 case cleanup:
763 db (DB_ACTIONS, "Cleanup\n");
764 break;
766 case handler:
767 db (DB_ACTIONS, "Handler, filter = %d\n", (int) action->ttype_filter);
768 break;
770 default:
771 db (DB_ACTIONS, "Err? Unexpected action kind !\n");
772 break;
774 #endif
777 /* Search the call_site_table of REGION for an entry appropriate for the
778 UW_CONTEXT's IP. If one is found, store the associated landing_pad
779 and action_table entry, and set the ACTION kind to unknown for further
780 analysis. Otherwise, set the ACTION kind to nothing.
782 There are two variants of this routine, depending on the underlying
783 mechanism (DWARF/SJLJ), which account for differences in the tables. */
785 #ifdef __USING_SJLJ_EXCEPTIONS__
787 #define __builtin_eh_return_data_regno(x) x
789 static void
790 get_call_site_action_for (_Unwind_Ptr call_site,
791 region_descriptor *region,
792 action_descriptor *action)
794 /* call_site is a direct index into the call-site table, with two special
795 values : -1 for no-action and 0 for "terminate". The latter should never
796 show up for Ada. To test for the former, beware that _Unwind_Ptr might
797 be unsigned. */
799 if ((int)call_site < 0)
801 action->kind = nothing;
803 else if (call_site == 0)
805 db (DB_ERR, "========> Err, null call_site for Ada/sjlj\n");
806 action->kind = nothing;
808 else
810 _uleb128_t cs_lp, cs_action;
811 const unsigned char *p;
813 /* Let the caller know there may be an action to take, but let it
814 determine the kind. */
815 action->kind = unknown;
817 /* We have a direct index into the call-site table, but this table is
818 made of leb128 values, the encoding length of which is variable. We
819 can't merely compute an offset from the index, then, but have to read
820 all the entries before the one of interest. */
821 p = region->call_site_table;
824 p = read_uleb128 (p, &cs_lp);
825 p = read_uleb128 (p, &cs_action);
827 while (--call_site);
829 action->landing_pad = cs_lp + 1;
831 if (cs_action)
832 action->table_entry = region->action_table + cs_action - 1;
833 else
834 action->table_entry = 0;
838 #else /* !__USING_SJLJ_EXCEPTIONS__ */
840 static void
841 get_call_site_action_for (_Unwind_Ptr ip,
842 region_descriptor *region,
843 action_descriptor *action)
845 const unsigned char *p = region->call_site_table;
847 /* Unless we are able to determine otherwise... */
848 action->kind = nothing;
850 db (DB_CSITE, "\n");
852 while (p < region->action_table)
854 _Unwind_Ptr cs_start, cs_len, cs_lp;
855 _uleb128_t cs_action;
857 /* Note that all call-site encodings are "absolute" displacements. */
858 p = read_encoded_value (0, region->call_site_encoding, p, &cs_start);
859 p = read_encoded_value (0, region->call_site_encoding, p, &cs_len);
860 #ifdef __CHERI_PURE_CAPABILITY__
861 // Single uleb128 value as the capability marker.
862 _Unwind_Ptr marker = 0;
863 p = read_encoded_value (0, DW_EH_PE_uleb128, p, &marker);
864 if (marker == 0xd)
866 /* 8-byte offset to the (indirected) capability. */
867 p = read_encoded_value (0, DW_EH_PE_pcrel | DW_EH_PE_udata8, p,
868 &cs_lp);
870 else if (marker)
872 /* Unsupported landing pad marker value. */
873 abort ();
875 else
876 cs_lp = 0; // No landing pad.
877 #else
878 p = read_encoded_value (0, region->call_site_encoding, p, &cs_lp);
879 #endif
881 p = read_uleb128 (p, &cs_action);
883 db (DB_CSITE,
884 "c_site @ %p (+%p), len = %p, lpad @ %p (+%p)\n",
885 (char *)region->base + cs_start, (void *)cs_start, (void *)cs_len,
886 (char *)region->lp_base + cs_lp, (void *)cs_lp);
888 /* The table is sorted, so if we've passed the IP, stop. */
889 if (ip < region->base + (size_t)cs_start)
890 break;
892 /* If we have a match, fill the ACTION fields accordingly. */
893 else if (ip < region->base + (size_t)cs_start + (size_t)cs_len)
895 /* Let the caller know there may be an action to take, but let it
896 determine the kind. */
897 action->kind = unknown;
899 if (cs_lp)
901 #ifdef __CHERI_PURE_CAPABILITY__
902 action->landing_pad = *(_Unwind_Ptr *)cs_lp;
903 #else
904 action->landing_pad = region->lp_base + cs_lp;
905 #endif
907 else
908 action->landing_pad = 0;
910 if (cs_action)
911 action->table_entry = region->action_table + cs_action - 1;
912 else
913 action->table_entry = 0;
915 db (DB_CSITE, "+++\n");
916 return;
920 db (DB_CSITE, "---\n");
923 #endif /* __USING_SJLJ_EXCEPTIONS__ */
925 /* With CHOICE an exception choice representing an "exception - when"
926 argument, and PROPAGATED_EXCEPTION a pointer to the currently propagated
927 occurrence, return true if the latter matches the former, that is, if
928 PROPAGATED_EXCEPTION is caught by the handling code controlled by CHOICE.
931 #define Is_Handled_By_Others __gnat_is_handled_by_others
932 #define Language_For __gnat_language_for
933 #define Foreign_Data_For __gnat_foreign_data_for
934 #define EID_For __gnat_eid_for
936 extern bool Is_Handled_By_Others (Exception_Id eid);
937 extern char Language_For (Exception_Id eid);
938 extern void *Foreign_Data_For (Exception_Id eid);
939 extern Exception_Id EID_For (_GNAT_Exception *e);
941 #define Foreign_Exception system__exceptions__foreign_exception
942 extern struct Exception_Data Foreign_Exception;
944 /* Return true iff the exception class of EXCEPT is EC. */
946 static int
947 exception_class_eq (const _GNAT_Exception *except,
948 const _Unwind_Exception_Class ec)
950 #ifdef __ARM_EABI_UNWINDER__
951 return memcmp (except->common.exception_class, ec, 8) == 0;
952 #else
953 return except->common.exception_class == ec;
954 #endif
957 /* Return how CHOICE matches PROPAGATED_EXCEPTION. */
959 static enum action_kind
960 is_handled_by (Exception_Id choice, _GNAT_Exception *propagated_exception)
962 /* All others choice match everything. */
963 if (choice == GNAT_ALL_OTHERS)
964 return handler;
966 /* GNAT exception occurrence. */
967 if (exception_class_eq (propagated_exception, GNAT_EXCEPTION_CLASS))
969 if (choice == GNAT_UNHANDLED_OTHERS)
970 return unhandler;
972 Exception_Id E = EID_For (propagated_exception);
974 /* Base matching rules: An exception data (id) matches itself, "when
975 all_others" matches anything and "when others" matches anything
976 unless explicitly stated otherwise in the propagated occurrence. */
977 if (choice == E || (choice == GNAT_OTHERS && Is_Handled_By_Others (E)))
978 return handler;
980 /* Otherwise, it doesn't match an Ada choice. */
981 return nothing;
984 /* All others and others choice match any foreign exception. */
985 if (choice == GNAT_ALL_OTHERS
986 || choice == GNAT_OTHERS
987 #ifndef CERT
988 || choice == &Foreign_Exception
989 #endif
991 return handler;
993 #ifndef CERT
994 /* C++ exception occurrences. */
995 if (exception_class_eq (propagated_exception, CXX_EXCEPTION_CLASS)
996 && Language_For (choice) == 'C')
998 void *choice_typeinfo = Foreign_Data_For (choice);
999 void *except_typeinfo =
1000 (((struct __cxa_exception *)
1001 ((_Unwind_Exception *)propagated_exception + 1)) - 1)
1002 ->exceptionType;
1004 /* Typeinfo are directly compared, which might not be correct if they
1005 aren't merged. ??? We should call the == operator if this module is
1006 compiled in C++. */
1007 if (choice_typeinfo == except_typeinfo)
1008 return handler;
1010 #endif
1012 return nothing;
1015 /* Fill out the ACTION to be taken from propagating UW_EXCEPTION up to
1016 UW_CONTEXT in REGION. */
1018 static void
1019 get_action_description_for (_Unwind_Ptr ip,
1020 _Unwind_Exception *uw_exception,
1021 _Unwind_Action uw_phase,
1022 region_descriptor *region,
1023 action_descriptor *action)
1025 _GNAT_Exception *gnat_exception = (_GNAT_Exception *) uw_exception;
1027 /* Search the call site table first, which may get us a landing pad as well
1028 as the head of an action record list. */
1029 get_call_site_action_for (ip, region, action);
1030 db_action_for (action, ip);
1032 /* If there is not even a call_site entry, we are done. */
1033 if (action->kind == nothing)
1034 return;
1036 /* Otherwise, check what we have at the place of the call site. */
1038 /* No landing pad => no cleanups or handlers. */
1039 if (action->landing_pad == 0)
1041 action->kind = nothing;
1042 return;
1045 /* Landing pad + null table entry => only cleanups. */
1046 else if (action->table_entry == 0)
1048 action->kind = cleanup;
1049 action->ttype_filter = cleanup_filter;
1050 /* The filter initialization is not strictly necessary, as cleanup-only
1051 landing pads don't look at the filter value. It is there to ensure
1052 we don't pass random values and so trigger potential confusion when
1053 installing the context later on. */
1054 return;
1057 /* Landing pad + Table entry => handlers + possible cleanups. */
1058 else
1060 const unsigned char * p = action->table_entry;
1061 _sleb128_t ar_filter, ar_disp;
1063 action->kind = nothing;
1065 while (1)
1067 p = read_sleb128 (p, &ar_filter);
1068 read_sleb128 (p, &ar_disp);
1069 /* Don't assign p here, as it will be incremented by ar_disp
1070 below. */
1072 /* Null filters are for cleanups. */
1073 if (ar_filter == cleanup_filter)
1075 action->kind = cleanup;
1076 action->ttype_filter = cleanup_filter;
1077 /* The filter initialization is required here, to ensure
1078 the target landing pad branches to the cleanup code if
1079 we happen not to find a matching handler. */
1082 /* Positive filters are for regular handlers. */
1083 else if (ar_filter > 0)
1085 /* Do not catch an exception if the _UA_FORCE_UNWIND flag is
1086 passed (to follow the ABI). */
1087 if (!(uw_phase & _UA_FORCE_UNWIND))
1089 enum action_kind act;
1091 /* See if the filter we have is for an exception which
1092 matches the one we are propagating. */
1093 Exception_Id choice
1094 = (Exception_Id) get_ttype_entry_for (region, ar_filter);
1096 act = is_handled_by (choice, gnat_exception);
1097 if (act != nothing)
1099 action->kind = act;
1100 action->ttype_filter = ar_filter;
1101 return;
1106 /* Negative filter values are for C++ exception specifications.
1107 Should not be there for Ada :/ */
1108 else
1109 db (DB_ERR, "========> Err, filter < 0 for Ada/dwarf\n");
1111 if (ar_disp == 0)
1112 return;
1114 p += ar_disp;
1119 /* Setup in UW_CONTEXT the eh return target IP and data registers, which will
1120 be restored with the others and retrieved by the landing pad once the jump
1121 occurred. */
1123 static void
1124 setup_to_install (_Unwind_Context *uw_context,
1125 _Unwind_Exception *uw_exception,
1126 _Unwind_Ptr uw_landing_pad,
1127 int uw_filter)
1129 /* 1/ exception object pointer, which might be provided back to
1130 _Unwind_Resume (and thus to this personality routine) if we are jumping
1131 to a cleanup. */
1132 _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (0),
1133 (_Unwind_Word)uw_exception);
1135 /* 2/ handler switch value register, which will also be used by the target
1136 landing pad to decide what action it shall take. */
1137 _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (1),
1138 (_Unwind_Word)uw_filter);
1140 /* Setup the address we should jump at to reach the code where there is the
1141 "something" we found. */
1142 _Unwind_SetIP (uw_context, uw_landing_pad);
1145 /* The following is defined from a-except.adb. Its purpose is to enable
1146 automatic backtraces upon exception raise, as provided through the
1147 GNAT.Traceback facilities. */
1148 extern void __gnat_notify_handled_exception (struct Exception_Occurrence *);
1149 extern void __gnat_notify_unhandled_exception (struct Exception_Occurrence *);
1151 /* Below is the eh personality routine per se. We currently assume that only
1152 GNU-Ada exceptions are met. */
1154 /* By default, the personality routine is public. */
1155 #define PERSONALITY_STORAGE
1157 #ifdef __USING_SJLJ_EXCEPTIONS__
1158 #define PERSONALITY_FUNCTION __gnat_personality_sj0
1159 #elif defined (__SEH__)
1160 #define PERSONALITY_FUNCTION __gnat_personality_imp
1161 /* The public personality routine for seh is __gnat_personality_seh0, defined
1162 below using the SEH convention. This is a wrapper around the GNU routine,
1163 which is static. */
1164 #undef PERSONALITY_STORAGE
1165 #define PERSONALITY_STORAGE static
1166 #else
1167 #define PERSONALITY_FUNCTION __gnat_personality_v0
1168 #endif
1170 #if defined (__ARM_EABI_UNWINDER__) \
1171 && (defined (IN_RTS) || GCC_VERSION > 9000)
1172 #define TARGET_ATTRIBUTE __attribute__((target ("general-regs-only")))
1173 #else
1174 #define TARGET_ATTRIBUTE
1175 #endif
1177 /* Code executed to continue unwinding. With the ARM unwinder, the
1178 personality routine must unwind one frame (per EHABI 7.3 4.). */
1180 static _Unwind_Reason_Code
1181 TARGET_ATTRIBUTE
1182 continue_unwind (struct _Unwind_Exception* ue_header ATTRIBUTE_UNUSED,
1183 struct _Unwind_Context* uw_context ATTRIBUTE_UNUSED)
1185 #ifdef __ARM_EABI_UNWINDER__
1186 if (__gnu_unwind_frame (ue_header, uw_context) != _URC_OK)
1187 return _URC_FAILURE;
1188 #endif
1189 return _URC_CONTINUE_UNWIND;
1192 /* Common code for the body of GNAT personality routine. This code is shared
1193 between all unwinders. */
1195 static _Unwind_Reason_Code
1196 TARGET_ATTRIBUTE
1197 personality_body (_Unwind_Action uw_phases,
1198 _Unwind_Exception *uw_exception,
1199 _Unwind_Context *uw_context)
1201 region_descriptor region;
1202 action_descriptor action;
1203 _Unwind_Ptr ip;
1205 /* Debug traces. */
1206 db_indent (DB_INDENT_RESET);
1207 db_phases (uw_phases);
1208 db_indent (DB_INDENT_INCREASE);
1210 /* Get the region description for the context we were provided with. This
1211 will tell us if there is some lsda, call_site, action and/or ttype data
1212 for the associated ip. */
1213 get_region_description_for (uw_context, &region);
1215 /* No LSDA => no handlers or cleanups => we shall unwind further up. */
1216 if (! region.lsda)
1217 return continue_unwind (uw_exception, uw_context);
1219 /* Get the instruction pointer. */
1220 ip = get_ip_from_context (uw_context);
1221 db_region_for (&region, ip);
1223 /* Search the call-site and action-record tables for the action associated
1224 with this IP. */
1225 get_action_description_for (ip, uw_exception, uw_phases, &region, &action);
1226 db_action_for (&action, ip);
1228 /* Whatever the phase, if there is nothing relevant in this frame,
1229 unwinding should just go on. */
1230 if (action.kind == nothing)
1231 return continue_unwind (uw_exception, uw_context);
1233 /* If we found something in search phase, we should return a code indicating
1234 what to do next depending on what we found. If we only have cleanups
1235 around, we shall try to unwind further up to find a handler, otherwise,
1236 tell we have a handler, which will trigger the second phase. */
1237 if (uw_phases & _UA_SEARCH_PHASE)
1239 if (action.kind == cleanup)
1241 return continue_unwind (uw_exception, uw_context);
1243 else
1245 #ifdef __ARM_EABI_UNWINDER__
1246 /* Though we do not use this field ourselves, initializing
1247 it is required by the ARM EH ABI before a personality
1248 function in phase1 returns _URC_HANDLER_FOUND, so that
1249 any personality function can use it in phase2 to test
1250 whether the handler frame was reached. */
1251 uw_exception->barrier_cache.sp
1252 = _Unwind_GetGR (uw_context, UNWIND_STACK_REG);
1253 #endif
1255 #ifndef CERT
1256 /* Trigger the appropriate notification routines before the second
1257 phase starts, when the stack is still intact. First install what
1258 needs to be installed in the current exception buffer and fetch
1259 the Ada occurrence pointer to use. */
1261 struct Exception_Occurrence *excep
1262 = __gnat_setup_current_excep (uw_exception, uw_phases);
1264 if (action.kind == unhandler)
1265 __gnat_notify_unhandled_exception (excep);
1266 else
1267 __gnat_notify_handled_exception (excep);
1268 #endif
1270 return _URC_HANDLER_FOUND;
1274 /* We found something in cleanup/handler phase, which might be the handler
1275 or a cleanup for a handled occurrence, or a cleanup for an unhandled
1276 occurrence (we are in a FORCED_UNWIND phase in this case). Install the
1277 context to get there. */
1279 setup_to_install
1280 (uw_context, uw_exception, action.landing_pad, action.ttype_filter);
1282 #ifndef CERT
1283 /* Write current exception so that it can be retrieved from Ada. It was
1284 already done during phase 1, but one or several exceptions may have been
1285 raised in cleanup handlers in between. */
1286 __gnat_setup_current_excep (uw_exception, uw_phases);
1287 #endif
1289 return _URC_INSTALL_CONTEXT;
1292 #ifndef __ARM_EABI_UNWINDER__
1293 typedef int version_arg_t;
1294 typedef _Unwind_Action phases_arg_t;
1296 PERSONALITY_STORAGE _Unwind_Reason_Code
1297 PERSONALITY_FUNCTION (version_arg_t, phases_arg_t,
1298 _Unwind_Exception_Class, _Unwind_Exception *,
1299 _Unwind_Context *);
1301 PERSONALITY_STORAGE _Unwind_Reason_Code
1302 PERSONALITY_FUNCTION (version_arg_t version_arg,
1303 phases_arg_t phases_arg,
1304 _Unwind_Exception_Class uw_exception_class
1305 ATTRIBUTE_UNUSED,
1306 _Unwind_Exception *uw_exception,
1307 _Unwind_Context *uw_context)
1309 /* Fetch the version and phases args with their nominal ABI types for later
1310 use. This is a noop everywhere except on ia64-vms when called from the
1311 Condition Handling Facility. */
1312 int uw_version = (int) version_arg;
1313 _Unwind_Action uw_phases = (_Unwind_Action) phases_arg;
1315 /* Check that we're called from the ABI context we expect. */
1316 if (uw_version != 1)
1317 return _URC_FATAL_PHASE1_ERROR;
1319 return personality_body (uw_phases, uw_exception, uw_context);
1322 #else /* __ARM_EABI_UNWINDER__ */
1324 PERSONALITY_STORAGE _Unwind_Reason_Code
1325 PERSONALITY_FUNCTION (_Unwind_State state,
1326 struct _Unwind_Exception* ue_header,
1327 struct _Unwind_Context* uw_context);
1329 PERSONALITY_STORAGE _Unwind_Reason_Code
1330 TARGET_ATTRIBUTE
1331 PERSONALITY_FUNCTION (_Unwind_State state,
1332 struct _Unwind_Exception* uw_exception,
1333 struct _Unwind_Context* uw_context)
1335 _Unwind_Action uw_phases;
1337 switch (state & _US_ACTION_MASK)
1339 case _US_VIRTUAL_UNWIND_FRAME:
1340 /* Phase 1. */
1341 uw_phases = _UA_SEARCH_PHASE;
1342 break;
1344 case _US_UNWIND_FRAME_STARTING:
1345 /* Phase 2, to call a cleanup. */
1346 uw_phases = _UA_CLEANUP_PHASE;
1347 #if 0
1348 /* ??? We don't use UA_HANDLER_FRAME (except to debug). Futhermore,
1349 barrier_cache.sp isn't yet set. */
1350 if (!(state & _US_FORCE_UNWIND)
1351 && (uw_exception->barrier_cache.sp
1352 == _Unwind_GetGR (uw_context, UNWIND_STACK_REG)))
1353 uw_phases |= _UA_HANDLER_FRAME;
1354 #endif
1355 break;
1357 case _US_UNWIND_FRAME_RESUME:
1358 /* Phase 2, called at the return of a cleanup. In the GNU
1359 implementation, there is nothing left to do, so we simply go on. */
1360 return continue_unwind (uw_exception, uw_context);
1362 default:
1363 return _URC_FAILURE;
1365 uw_phases |= (state & _US_FORCE_UNWIND);
1367 /* The dwarf unwinder assumes the context structure holds things like the
1368 function and LSDA pointers. The ARM implementation caches these in
1369 the exception header (UCB). To avoid rewriting everything we make a
1370 virtual scratch register point at the UCB. This is a GNU specific
1371 requirement. */
1372 _Unwind_SetGR (uw_context, UNWIND_POINTER_REG, (_Unwind_Ptr) uw_exception);
1374 return personality_body (uw_phases, uw_exception, uw_context);
1376 #endif /* __ARM_EABI_UNWINDER__ */
1378 /* Callback routine called by Unwind_ForcedUnwind to execute all the cleanup
1379 before exiting the task. */
1381 #ifndef CERT
1382 _Unwind_Reason_Code
1383 __gnat_cleanupunwind_handler (int version ATTRIBUTE_UNUSED,
1384 _Unwind_Action phases,
1385 _Unwind_Exception_Class eclass ATTRIBUTE_UNUSED,
1386 struct _Unwind_Exception *exception,
1387 struct _Unwind_Context *context ATTRIBUTE_UNUSED,
1388 void *arg ATTRIBUTE_UNUSED)
1390 /* Terminate when the end of the stack is reached. */
1391 if ((phases & _UA_END_OF_STACK) != 0
1392 #if defined (__ia64__) && defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
1393 /* Strictely follow the ia64 ABI: when end of stack is reached,
1394 the callback will be called with a NULL stack pointer.
1395 No need for that when using libgcc unwinder. */
1396 || _Unwind_GetGR (context, 12) == 0
1397 #endif
1399 __gnat_unhandled_except_handler (exception);
1401 /* We know there is at least one cleanup further up. Return so that it
1402 is searched and entered, after which Unwind_Resume will be called
1403 and this hook will gain control again. */
1404 return _URC_NO_REASON;
1406 #endif
1408 /* Define the consistently named wrappers imported by Propagate_Exception. */
1410 _Unwind_Reason_Code
1411 __gnat_Unwind_RaiseException (_Unwind_Exception *e)
1413 #ifdef NO_EXCEPTION_PROPAGATION
1414 abort();
1415 #endif
1417 #ifdef __USING_SJLJ_EXCEPTIONS__
1418 return _Unwind_SjLj_RaiseException (e);
1419 #else
1420 return _Unwind_RaiseException (e);
1421 #endif
1424 _Unwind_Reason_Code
1425 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e ATTRIBUTE_UNUSED,
1426 _Unwind_Stop_Fn handler ATTRIBUTE_UNUSED,
1427 void *argument ATTRIBUTE_UNUSED)
1429 #ifdef __USING_SJLJ_EXCEPTIONS__
1431 # if defined (__APPLE__) && defined (__arm__)
1432 /* There is not ForcedUnwind routine in arm-darwin system library. */
1433 return _URC_FATAL_PHASE1_ERROR;
1434 # else
1435 return _Unwind_SjLj_ForcedUnwind (e, handler, argument);
1436 # endif
1438 #else
1439 return _Unwind_ForcedUnwind (e, handler, argument);
1440 #endif
1443 #if defined (__SEH__) && !defined (__USING_SJLJ_EXCEPTIONS__)
1445 #define STATUS_USER_DEFINED (1U << 29)
1447 /* From unwind-seh.c. */
1448 #define GCC_MAGIC (('G' << 16) | ('C' << 8) | 'C')
1449 #define GCC_EXCEPTION(TYPE) \
1450 (STATUS_USER_DEFINED | ((TYPE) << 24) | GCC_MAGIC)
1451 #define STATUS_GCC_THROW GCC_EXCEPTION (0)
1453 struct Exception_Data *
1454 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg);
1456 struct _Unwind_Exception *
1457 __gnat_create_machine_occurrence_from_signal_handler (Exception_Id,
1458 const char *);
1460 /* Unwind opcodes. */
1461 #define UWOP_PUSH_NONVOL 0
1462 #define UWOP_ALLOC_LARGE 1
1463 #define UWOP_ALLOC_SMALL 2
1464 #define UWOP_SET_FPREG 3
1465 #define UWOP_SAVE_NONVOL 4
1466 #define UWOP_SAVE_NONVOL_FAR 5
1467 #define UWOP_SAVE_XMM128 8
1468 #define UWOP_SAVE_XMM128_FAR 9
1469 #define UWOP_PUSH_MACHFRAME 10
1471 /* Modify the IP value saved in the machine frame. This is really a kludge,
1472 that will be removed if we could propagate the Windows exception (and not
1473 the GCC one).
1475 What is very wrong is that the Windows unwinder will try to decode the
1476 instruction at IP, which isn't valid anymore after the adjustment. */
1478 static void
1479 __gnat_adjust_context (unsigned char *unw, ULONG64 rsp)
1481 unsigned int len;
1483 /* Version 1 or 2. */
1484 if (unw[0] != 1 && unw[0] != 2)
1485 return;
1486 /* No flags, no prologue. */
1487 if (unw[1] != 0)
1488 return;
1489 len = unw[2];
1490 /* No frame. */
1491 if (unw[3] != 0)
1492 return;
1493 /* ??? Skip the first 2 undocumented opcodes for version 2. */
1494 if (unw[0] == 2)
1495 unw += 8;
1496 else
1497 unw += 4;
1498 while (len > 0)
1500 /* Offset in prologue = 0. */
1501 if (unw[0] != 0)
1502 return;
1503 switch (unw[1] & 0xf)
1505 case UWOP_ALLOC_LARGE:
1506 /* Expect < 512KB. */
1507 if ((unw[1] & 0xf0) != 0)
1508 return;
1509 rsp += *(unsigned short *)(unw + 2) * 8;
1510 len--;
1511 unw += 2;
1512 break;
1513 case UWOP_SAVE_NONVOL:
1514 case UWOP_SAVE_XMM128:
1515 len--;
1516 unw += 2;
1517 break;
1518 case UWOP_PUSH_MACHFRAME:
1520 ULONG64 *rip;
1521 rip = (ULONG64 *)rsp;
1522 if ((unw[1] & 0xf0) == 0x10)
1523 rip++;
1524 /* Adjust rip. */
1525 (*rip)++;
1527 return;
1528 default:
1529 /* Unexpected. */
1530 return;
1532 unw += 2;
1533 len--;
1537 EXCEPTION_DISPOSITION
1538 __gnat_personality_seh0 (PEXCEPTION_RECORD ms_exc, void *this_frame,
1539 PCONTEXT ms_orig_context,
1540 PDISPATCHER_CONTEXT ms_disp)
1542 /* Possibly transform run-time errors into Ada exceptions. */
1543 if (!(ms_exc->ExceptionCode & STATUS_USER_DEFINED))
1545 struct Exception_Data *exception;
1546 const char *msg;
1547 ULONG64 excpip = (ULONG64) ms_exc->ExceptionAddress;
1549 if (excpip != 0
1550 && excpip >= (ms_disp->ImageBase
1551 + ms_disp->FunctionEntry->BeginAddress)
1552 && excpip < (ms_disp->ImageBase
1553 + ms_disp->FunctionEntry->EndAddress))
1555 /* This is a fault in this function. We need to adjust the return
1556 address before raising the GCC exception. In order to do that,
1557 we need to locate the machine frame that has been pushed onto
1558 the stack in response to the hardware exception, so we will do
1559 a private unwinding from here, i.e. the frame of the personality
1560 routine, up to the frame immediately following the frame of this
1561 function. This frame corresponds to a dummy prologue which is
1562 never actually executed but instead appears before the real entry
1563 point of an interrupt routine and exists only to provide a place
1564 to simulate the push of a machine frame. */
1565 CONTEXT context;
1566 PRUNTIME_FUNCTION mf_func = NULL;
1567 ULONG64 mf_imagebase;
1568 ULONG64 mf_rsp = 0;
1570 /* Get the current context. */
1571 RtlCaptureContext (&context);
1573 while (1)
1575 PRUNTIME_FUNCTION RuntimeFunction;
1576 ULONG64 ImageBase;
1577 VOID *HandlerData;
1578 ULONG64 EstablisherFrame;
1580 /* Get function metadata. */
1581 RuntimeFunction
1582 = RtlLookupFunctionEntry (context.Rip, &ImageBase,
1583 ms_disp->HistoryTable);
1585 /* Stop once we reached the frame of this function. */
1586 if (RuntimeFunction == ms_disp->FunctionEntry)
1587 break;
1589 mf_func = RuntimeFunction;
1590 mf_imagebase = ImageBase;
1591 mf_rsp = context.Rsp;
1593 if (RuntimeFunction)
1595 /* Unwind. */
1596 RtlVirtualUnwind (0, ImageBase, context.Rip, RuntimeFunction,
1597 &context, &HandlerData, &EstablisherFrame,
1598 NULL);
1600 else
1602 /* In case of failure, assume this is a leaf function. */
1603 context.Rip = *(ULONG64 *) context.Rsp;
1604 context.Rsp += 8;
1607 /* 0 means bottom of the stack. */
1608 if (context.Rip == 0)
1610 mf_func = NULL;
1611 break;
1615 /* If we have found the machine frame, adjust the return address. */
1616 if (mf_func != NULL)
1617 __gnat_adjust_context
1618 ((unsigned char *)(mf_imagebase + mf_func->UnwindData), mf_rsp);
1621 exception = __gnat_map_SEH (ms_exc, &msg);
1622 if (exception != NULL)
1624 /* Directly convert the system exception into a GCC one.
1626 This is really breaking the API, but is necessary for stack size
1627 reasons: the normal way is to call Raise_From_Signal_Handler,
1628 which builds the exception and calls _Unwind_RaiseException,
1629 which unwinds the stack and will call this personality routine.
1630 But the Windows unwinder needs about 2KB of stack. */
1631 struct _Unwind_Exception *exc
1632 = __gnat_create_machine_occurrence_from_signal_handler (exception,
1633 msg);
1634 memset (exc->private_, 0, sizeof (exc->private_));
1635 ms_exc->ExceptionCode = STATUS_GCC_THROW;
1636 ms_exc->NumberParameters = 1;
1637 ms_exc->ExceptionInformation[0] = (ULONG_PTR)exc;
1642 return
1643 _GCC_specific_handler (ms_exc, this_frame, ms_orig_context, ms_disp,
1644 PERSONALITY_FUNCTION);
1647 /* Define __gnat_personality_v0 for convenience */
1649 PERSONALITY_STORAGE ATTRIBUTE_UNUSED _Unwind_Reason_Code
1650 __gnat_personality_v0 (version_arg_t version_arg,
1651 phases_arg_t phases_arg,
1652 _Unwind_Exception_Class uw_exception_class,
1653 _Unwind_Exception *uw_exception,
1654 _Unwind_Context *uw_context)
1656 return PERSONALITY_FUNCTION
1657 (version_arg, phases_arg, uw_exception_class, uw_exception, uw_context);
1660 #endif /* SEH */
1662 #if !defined (__USING_SJLJ_EXCEPTIONS__)
1663 /* Size of the _Unwind_Exception structure. This is used by g-cppexc to get
1664 the offset to the C++ object. */
1666 const int __gnat_unwind_exception_size = sizeof (_Unwind_Exception);
1667 #endif
1669 #ifdef __cplusplus
1671 #endif