1 /****************************************************************************
3 * GNAT COMPILER COMPONENTS *
7 * C Implementation File *
9 * Copyright (C) 1992-2019, Free Software Foundation, Inc. *
11 * GNAT is free software; you can redistribute it and/or modify it under *
12 * terms of the GNU General Public License as published by the Free Soft- *
13 * ware Foundation; either version 3, or (at your option) any later ver- *
14 * sion. GNAT is distributed in the hope that it will be useful, but WITH- *
15 * OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
16 * or FITNESS FOR A PARTICULAR PURPOSE. *
18 * As a special exception under Section 7 of GPL version 3, you are granted *
19 * additional permissions described in the GCC Runtime Library Exception, *
20 * version 3.1, as published by the Free Software Foundation. *
22 * You should have received a copy of the GNU General Public License and *
23 * a copy of the GCC Runtime Library Exception along with this program; *
24 * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see *
25 * <http://www.gnu.org/licenses/>. *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
30 ****************************************************************************/
32 /* Code related to the integration of the GCC mechanism for exception
36 /* For gnat1/gnatbind compilation: use host headers. */
39 /* Don't use fancy_abort. */
42 # if !defined(CERT) && !defined(STANDALONE)
47 # define HAVE_GETIPINFO 1
64 /* On MacOS X, versions older than 10.5 don't export _Unwind_GetIPInfo. */
66 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
67 #define HAVE_GETIPINFO 1
71 #if defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
72 /* HP-UX B.11.31 ia64 libunwind doesn't have _Unwind_GetIPInfo. */
74 #define _UA_END_OF_STACK 0
77 /* The names of a couple of "standard" routines for unwinding/propagation
78 actually vary depending on the underlying GCC scheme for exception handling
79 (SJLJ or DWARF). We need a consistently named interface to import from
80 a-except, so wrappers are defined here. */
83 /* For gnat1/gnatbind compilation: cannot use unwind.h, as it is for the
84 target. So mimic configure...
85 This is a hack ???, the real fix is to link gnat1/gnatbind with the
86 runtime of the build compiler. */
87 # ifdef EH_MECHANISM_arm
88 # include "config/arm/unwind-arm.h"
90 # include "unwind-generic.h"
100 typedef struct _Unwind_Context _Unwind_Context
;
101 typedef struct _Unwind_Exception _Unwind_Exception
;
104 __gnat_Unwind_RaiseException (_Unwind_Exception
*);
107 __gnat_Unwind_ForcedUnwind (_Unwind_Exception
*, _Unwind_Stop_Fn
, void *);
109 extern struct Exception_Occurrence
*
110 __gnat_setup_current_excep (_Unwind_Exception
*, _Unwind_Action
);
112 extern void __gnat_unhandled_except_handler (_Unwind_Exception
*);
115 /* Called in case of error during propagation. */
116 extern void __gnat_raise_abort (void) __attribute__ ((noreturn
));
117 #define abort() __gnat_raise_abort()
119 #elif defined(STANDALONE)
124 #include "unwind-pe.h"
126 #ifdef __ARM_EABI_UNWINDER__
131 /* The known and handled exception classes. */
133 #ifdef __ARM_EABI_UNWINDER__
134 #define CXX_EXCEPTION_CLASS "GNUCC++"
135 #define GNAT_EXCEPTION_CLASS "GNU-Ada"
137 #define CXX_EXCEPTION_CLASS 0x474e5543432b2b00ULL
138 #define GNAT_EXCEPTION_CLASS 0x474e552d41646100ULL
141 /* Structure of a C++ exception, represented as a C structure... See
142 unwind-cxx.h for the full definition. */
144 struct __cxa_exception
147 void (*exceptionDestructor
)(void *);
149 void (*unexpectedHandler
)();
150 void (*terminateHandler
)();
152 struct __cxa_exception
*nextException
;
156 #ifdef __ARM_EABI_UNWINDER__
157 struct __cxa_exception
* nextPropagatingException
;
159 int propagationCount
;
161 int handlerSwitchValue
;
162 const unsigned char *actionRecord
;
163 const unsigned char *languageSpecificData
;
164 _Unwind_Ptr catchTemp
;
168 _Unwind_Exception unwindHeader
;
171 /* --------------------------------------------------------------
172 -- The DB stuff below is there for debugging purposes only. --
173 -------------------------------------------------------------- */
177 #define DB_PHASES 0x1
179 #define DB_ACTIONS 0x4
180 #define DB_REGIONS 0x8
182 #define DB_ERR 0x1000
184 /* The "action" stuff below is also there for debugging purposes only. */
188 _Unwind_Action phase
;
189 const char * description
;
192 static const phase_descriptor phase_descriptors
[]
193 = {{ _UA_SEARCH_PHASE
, "SEARCH_PHASE" },
194 { _UA_CLEANUP_PHASE
, "CLEANUP_PHASE" },
195 { _UA_HANDLER_FRAME
, "HANDLER_FRAME" },
196 { _UA_FORCE_UNWIND
, "FORCE_UNWIND" },
200 db_accepted_codes (void)
202 static int accepted_codes
= -1;
204 if (accepted_codes
== -1)
206 char * db_env
= (char *) getenv ("EH_DEBUG");
208 accepted_codes
= db_env
? (atoi (db_env
) | DB_ERR
) : 0;
209 /* Arranged for ERR stuff to always be visible when the variable
210 is defined. One may just set the variable to 0 to see the ERR
214 return accepted_codes
;
217 #define DB_INDENT_INCREASE 0x01
218 #define DB_INDENT_DECREASE 0x02
219 #define DB_INDENT_OUTPUT 0x04
220 #define DB_INDENT_NEWLINE 0x08
221 #define DB_INDENT_RESET 0x10
223 #define DB_INDENT_UNIT 8
226 db_indent (int requests
)
228 static int current_indentation_level
= 0;
230 if (requests
& DB_INDENT_RESET
)
231 current_indentation_level
= 0;
233 if (requests
& DB_INDENT_INCREASE
)
234 current_indentation_level
++;
236 if (requests
& DB_INDENT_DECREASE
)
237 current_indentation_level
--;
239 if (requests
& DB_INDENT_NEWLINE
)
240 fprintf (stderr
, "\n");
242 if (requests
& DB_INDENT_OUTPUT
)
243 fprintf (stderr
, "%*s", current_indentation_level
* DB_INDENT_UNIT
, " ");
246 static void ATTRIBUTE_PRINTF_2
247 db (int db_code
, const char * msg_format
, ...)
249 if (db_accepted_codes () & db_code
)
253 db_indent (DB_INDENT_OUTPUT
);
255 va_start (msg_args
, msg_format
);
256 vfprintf (stderr
, msg_format
, msg_args
);
262 db_phases (int phases
)
264 const phase_descriptor
*a
= phase_descriptors
;
266 if (! (db_accepted_codes () & DB_PHASES
))
269 db (DB_PHASES
, "\n");
271 for (; a
->description
!= 0; a
++)
272 if (phases
& a
->phase
)
273 db (DB_PHASES
, "%s ", a
->description
);
275 db (DB_PHASES
, " :\n");
277 #else /* !inhibit_libc */
281 #endif /* !inhibit_libc */
283 /* ---------------------------------------------------------------
284 -- Now come a set of useful structures and helper routines. --
285 --------------------------------------------------------------- */
287 /* There are three major runtime tables involved, generated by the
288 GCC back-end. Contents slightly vary depending on the underlying
289 implementation scheme (dwarf zero cost / sjlj).
291 =======================================
292 * Tables for the dwarf zero cost case *
293 =======================================
295 They are fully documented in:
296 http://sourcery.mentor.com/public/cxx-abi/exceptions.pdf
297 Here is a shorter presentation, with some specific comments for Ada.
300 -------------------------------------------------------------------
301 * region-start | region-length | landing-pad | first-action-index *
302 -------------------------------------------------------------------
304 Identify possible actions to be taken and where to resume control
305 for that when an exception propagates through a pc inside the region
306 delimited by start and length.
308 A null landing-pad indicates that nothing is to be done.
310 Otherwise, first-action-index provides an entry into the action[]
311 table which heads a list of possible actions to be taken (see below).
313 If it is determined that indeed an action should be taken, that
314 is, if one action filter matches the exception being propagated,
315 then control should be transferred to landing-pad.
317 A null first-action-index indicates that there are only cleanups
321 -------------------------------
322 * action-filter | next-action *
323 -------------------------------
325 This table contains lists (called action chains) of possible actions
326 associated with call-site entries described in the call-site [] table.
327 There is at most one action list per call-site entry. It is SLEB128
330 A null action-filter indicates a cleanup.
332 Non null action-filters provide an index into the ttypes [] table
333 (see below), from which information may be retrieved to check if it
334 matches the exception being propagated.
337 means there is a regular handler to be run The value is also passed
338 to the landing pad to dispatch the exception.
341 means there is a some "exception_specification" data to retrieve,
342 which is only relevant for C++ and should never show up for Ada.
343 (Exception specification specifies which exceptions can be thrown
344 by a function. Such filter is emitted around the body of C++
345 functions defined like:
346 void foo ([...]) throw (A, B) { [...] }
347 These can be viewed as negativ filter: the landing pad is branched
348 to for exceptions that doesn't match the filter and usually aborts
352 points to the next entry in the list using a relative byte offset. 0
353 indicates there is no other entry.
360 This table is an array of addresses.
362 A null value indicates a catch-all handler. (Not used by Ada)
364 Non null values are used to match the exception being propagated:
365 In C++ this is a pointer to some rtti data, while in Ada this is an
366 exception id (with a fake id for others).
368 For C++, this table is actually also used to store "exception
369 specification" data. The differentiation between the two kinds
370 of entries is made by the sign of the associated action filter,
371 which translates into positive or negative offsets from the
372 so called base of the table:
374 Exception Specification data is stored at positive offsets from
375 the ttypes table base, which Exception Type data is stored at
378 ---------------------------------------------------------------------------
380 Here is a quick summary of the tables organization:
382 +-- Unwind_Context (pc, ...)
388 | +=============================================================+
389 | | region-start + length | landing-pad | first-action-index |
390 | +=============================================================+
391 +-> | pc range 0 => no-action 0 => cleanups only |
392 | !0 => jump @ N --+ |
393 +====================================================== | ====+
398 +==========================================================+ |
399 | action-filter | next-action | |
400 +==========================================================+ |
402 | >0 => ttype index for handler ------+ 0 => end of chain | <-+
403 | <0 => ttype index for spec data | |
404 +==================================== | ===================+
408 | Offset negated from
409 +=====================+ | the actual base.
411 +============+=====================+ |
413 | ... | exception id | <---+
415 | handlers +---------------------+
419 +============+=====================+ <<------ Table base
421 | specs | ... | (should not see negative filter
422 | ... | ... | values for Ada).
423 +============+=====================+
426 ============================
427 * Tables for the sjlj case *
428 ============================
430 So called "function contexts" are pushed on a context stack by calls to
431 _Unwind_SjLj_Register on function entry, and popped off at exit points by
432 calls to _Unwind_SjLj_Unregister. The current call_site for a function is
433 updated in the function context as the function's code runs along.
435 The generic unwinding engine in _Unwind_RaiseException walks the function
436 context stack and not the actual call chain.
438 The ACTION and TTYPES tables remain unchanged, which allows to search them
439 during the propagation phase to determine whether or not the propagated
440 exception is handled somewhere. When it is, we only "jump" up once directly
441 to the context where the handler will be found. Besides, this allows "break
442 exception unhandled" to work also
444 The CALL-SITE table is setup differently, though: the pc attached to the
445 unwind context is a direct index into the table, so the entries in this
446 table do not hold region bounds any more.
448 A special index (-1) is used to indicate that no action is possibly
449 connected with the context at hand, so null landing pads cannot appear
452 Additionally, landing pad values in the table do not represent code address
453 to jump at, but so called "dispatch" indices used by a common landing pad
454 for the function to switch to the appropriate post-landing-pad.
456 +-- Unwind_Context (pc, ...)
458 | pc = call-site index
459 | 0 => terminate (should not see this for Ada)
464 | +=====================================+
465 | | landing-pad | first-action-index |
466 | +=====================================+
467 +-> | 0 => cleanups only |
469 +=====================================+
472 ===================================
473 * Basic organization of this unit *
474 ===================================
476 The major point of this unit is to provide an exception propagation
477 personality routine for Ada. This is __gnat_personality_v0.
479 It is provided with a pointer to the propagated exception, an unwind
480 context describing a location the propagation is going through, and a
481 couple of other arguments including a description of the current
484 It shall return to the generic propagation engine what is to be performed
485 next, after possible context adjustments, depending on what it finds in the
486 traversed context (a handler for the exception, a cleanup, nothing, ...),
487 and on the propagation phase.
489 A number of structures and subroutines are used for this purpose, as
492 o region_descriptor: General data associated with the context (base pc,
493 call-site table, action table, ttypes table, ...)
495 o action_descriptor: Data describing the action to be taken for the
496 propagated exception in the provided context (kind of action: nothing,
497 handler, cleanup; pointer to the action table entry, ...).
503 Propagate_Exception (a-exexpr.adb)
506 _Unwind_RaiseException (libgcc)
510 +--> __gnat_personality_v0 (context, exception)
512 +--> get_region_description_for (context)
514 +--> get_action_description_for (ip, exception, region)
516 | +--> get_call_site_action_for (context, region)
517 | (one version for each underlying scheme)
519 +--> setup_to_install (context)
521 This unit is inspired from the C++ version found in eh_personality.cc,
522 part of libstdc++-v3.
527 /* This is an incomplete "proxy" of the structure of exception objects as
528 built by the GNAT runtime library. Accesses to other fields than the common
529 header are performed through subprogram calls to alleviate the need of an
530 exact counterpart here and potential alignment/size issues for the common
531 header. See a-exexpr.adb. */
535 _Unwind_Exception common
;
536 /* ABI header, maximally aligned. */
539 /* The two constants below are specific ttype identifiers for special
540 exception ids. Their type should match what a-exexpr exports. */
542 extern const int __gnat_others_value
;
543 #define GNAT_OTHERS ((_Unwind_Ptr) &__gnat_others_value)
545 extern const int __gnat_all_others_value
;
546 #define GNAT_ALL_OTHERS ((_Unwind_Ptr) &__gnat_all_others_value)
548 extern const int __gnat_unhandled_others_value
;
549 #define GNAT_UNHANDLED_OTHERS ((_Unwind_Ptr) &__gnat_unhandled_others_value)
551 /* Describe the useful region data associated with an unwind context. */
555 /* The base pc of the region. */
558 /* Pointer to the Language Specific Data for the region. */
561 /* Call-Site data associated with this region. */
562 unsigned char call_site_encoding
;
563 const unsigned char *call_site_table
;
565 /* The base to which are relative landing pad offsets inside the call-site
569 /* Action-Table associated with this region. */
570 const unsigned char *action_table
;
572 /* Ttype data associated with this region. */
573 unsigned char ttype_encoding
;
574 const unsigned char *ttype_table
;
575 _Unwind_Ptr ttype_base
;
579 /* Extract and adjust the IP (instruction pointer) from an exception
583 get_ip_from_context (_Unwind_Context
*uw_context
)
585 int ip_before_insn
= 0;
586 #ifdef HAVE_GETIPINFO
587 _Unwind_Ptr ip
= _Unwind_GetIPInfo (uw_context
, &ip_before_insn
);
589 _Unwind_Ptr ip
= _Unwind_GetIP (uw_context
);
591 /* Subtract 1 if necessary because GetIPInfo yields a call return address
592 in this case, while we are interested in information for the call point.
593 This does not always yield the exact call instruction address but always
594 brings the IP back within the corresponding region. */
602 db_region_for (region_descriptor
*region
, _Unwind_Ptr ip
)
605 if (! (db_accepted_codes () & DB_REGIONS
))
608 db (DB_REGIONS
, "For ip @ %p => ", (void *)ip
);
611 db (DB_REGIONS
, "lsda @ %p", (void *)region
->lsda
);
613 db (DB_REGIONS
, "no lsda");
615 db (DB_REGIONS
, "\n");
619 /* Retrieve the ttype entry associated with FILTER in the REGION's
623 get_ttype_entry_for (region_descriptor
*region
, long filter
)
625 _Unwind_Ptr ttype_entry
;
627 filter
*= size_of_encoded_value (region
->ttype_encoding
);
628 read_encoded_value_with_base
629 (region
->ttype_encoding
, region
->ttype_base
,
630 region
->ttype_table
- filter
, &ttype_entry
);
635 /* Fill out the REGION descriptor for the provided UW_CONTEXT. */
638 get_region_description_for (_Unwind_Context
*uw_context
,
639 region_descriptor
*region
)
641 const unsigned char * p
;
643 unsigned char lpbase_encoding
;
645 /* Get the base address of the lsda information. If the provided context
646 is null or if there is no associated language specific data, there's
647 nothing we can/should do. */
649 = (_Unwind_Ptr
) (uw_context
650 ? _Unwind_GetLanguageSpecificData (uw_context
) : 0);
655 /* Parse the lsda and fill the region descriptor. */
656 p
= (const unsigned char *)region
->lsda
;
658 region
->base
= _Unwind_GetRegionStart (uw_context
);
660 /* Find @LPStart, the base to which landing pad offsets are relative. */
661 lpbase_encoding
= *p
++;
662 if (lpbase_encoding
!= DW_EH_PE_omit
)
663 p
= read_encoded_value
664 (uw_context
, lpbase_encoding
, p
, ®ion
->lp_base
);
666 region
->lp_base
= region
->base
;
668 /* Find @TType, the base of the handler and exception spec type data. */
669 region
->ttype_encoding
= *p
++;
670 if (region
->ttype_encoding
!= DW_EH_PE_omit
)
672 p
= read_uleb128 (p
, &tmp
);
673 region
->ttype_table
= p
+ tmp
;
676 region
->ttype_table
= 0;
679 = base_of_encoded_value (region
->ttype_encoding
, uw_context
);
681 /* Get the encoding and length of the call-site table; the action table
682 immediately follows. */
683 region
->call_site_encoding
= *p
++;
684 region
->call_site_table
= read_uleb128 (p
, &tmp
);
686 region
->action_table
= region
->call_site_table
+ tmp
;
690 /* Describe an action to be taken when propagating an exception up to
695 /* Found some call site base data, but need to analyze further
696 before being able to decide. */
699 /* There is nothing relevant in the context at hand. */
702 /* There are only cleanups to run in this context. */
705 /* There is a handler for the exception in this context. */
708 /* There is a handler for the exception, but it is only for catching
709 unhandled exceptions. */
713 /* filter value for cleanup actions. */
714 static const int cleanup_filter
= 0;
718 /* The kind of action to be taken. */
719 enum action_kind kind
;
721 /* A pointer to the action record entry. */
722 const unsigned char *table_entry
;
724 /* Where we should jump to actually take an action (trigger a cleanup or an
725 exception handler). */
726 _Unwind_Ptr landing_pad
;
728 /* If we have a handler matching our exception, these are the filter to
729 trigger it and the corresponding id. */
730 _Unwind_Sword ttype_filter
;
735 db_action_for (action_descriptor
*action
, _Unwind_Ptr ip
)
738 db (DB_ACTIONS
, "For ip @ %p => ", (void *)ip
);
740 switch (action
->kind
)
743 db (DB_ACTIONS
, "lpad @ %p, record @ %p\n",
744 (void *) action
->landing_pad
, action
->table_entry
);
748 db (DB_ACTIONS
, "Nothing\n");
752 db (DB_ACTIONS
, "Cleanup\n");
756 db (DB_ACTIONS
, "Handler, filter = %d\n", (int) action
->ttype_filter
);
760 db (DB_ACTIONS
, "Err? Unexpected action kind !\n");
766 /* Search the call_site_table of REGION for an entry appropriate for the
767 UW_CONTEXT's IP. If one is found, store the associated landing_pad
768 and action_table entry, and set the ACTION kind to unknown for further
769 analysis. Otherwise, set the ACTION kind to nothing.
771 There are two variants of this routine, depending on the underlying
772 mechanism (DWARF/SJLJ), which account for differences in the tables. */
774 #ifdef __USING_SJLJ_EXCEPTIONS__
776 #define __builtin_eh_return_data_regno(x) x
779 get_call_site_action_for (_Unwind_Ptr call_site
,
780 region_descriptor
*region
,
781 action_descriptor
*action
)
783 /* call_site is a direct index into the call-site table, with two special
784 values : -1 for no-action and 0 for "terminate". The latter should never
785 show up for Ada. To test for the former, beware that _Unwind_Ptr might
788 if ((int)call_site
< 0)
790 action
->kind
= nothing
;
792 else if (call_site
== 0)
794 db (DB_ERR
, "========> Err, null call_site for Ada/sjlj\n");
795 action
->kind
= nothing
;
799 _uleb128_t cs_lp
, cs_action
;
800 const unsigned char *p
;
802 /* Let the caller know there may be an action to take, but let it
803 determine the kind. */
804 action
->kind
= unknown
;
806 /* We have a direct index into the call-site table, but this table is
807 made of leb128 values, the encoding length of which is variable. We
808 can't merely compute an offset from the index, then, but have to read
809 all the entries before the one of interest. */
810 p
= region
->call_site_table
;
813 p
= read_uleb128 (p
, &cs_lp
);
814 p
= read_uleb128 (p
, &cs_action
);
818 action
->landing_pad
= cs_lp
+ 1;
821 action
->table_entry
= region
->action_table
+ cs_action
- 1;
823 action
->table_entry
= 0;
827 #else /* !__USING_SJLJ_EXCEPTIONS__ */
830 get_call_site_action_for (_Unwind_Ptr ip
,
831 region_descriptor
*region
,
832 action_descriptor
*action
)
834 const unsigned char *p
= region
->call_site_table
;
836 /* Unless we are able to determine otherwise... */
837 action
->kind
= nothing
;
841 while (p
< region
->action_table
)
843 _Unwind_Ptr cs_start
, cs_len
, cs_lp
;
844 _uleb128_t cs_action
;
846 /* Note that all call-site encodings are "absolute" displacements. */
847 p
= read_encoded_value (0, region
->call_site_encoding
, p
, &cs_start
);
848 p
= read_encoded_value (0, region
->call_site_encoding
, p
, &cs_len
);
849 p
= read_encoded_value (0, region
->call_site_encoding
, p
, &cs_lp
);
850 p
= read_uleb128 (p
, &cs_action
);
853 "c_site @ %p (+%p), len = %p, lpad @ %p (+%p)\n",
854 (char *)region
->base
+ cs_start
, (void *)cs_start
, (void *)cs_len
,
855 (char *)region
->lp_base
+ cs_lp
, (void *)cs_lp
);
857 /* The table is sorted, so if we've passed the IP, stop. */
858 if (ip
< region
->base
+ cs_start
)
861 /* If we have a match, fill the ACTION fields accordingly. */
862 else if (ip
< region
->base
+ cs_start
+ cs_len
)
864 /* Let the caller know there may be an action to take, but let it
865 determine the kind. */
866 action
->kind
= unknown
;
869 action
->landing_pad
= region
->lp_base
+ cs_lp
;
871 action
->landing_pad
= 0;
874 action
->table_entry
= region
->action_table
+ cs_action
- 1;
876 action
->table_entry
= 0;
878 db (DB_CSITE
, "+++\n");
883 db (DB_CSITE
, "---\n");
886 #endif /* __USING_SJLJ_EXCEPTIONS__ */
888 /* With CHOICE an exception choice representing an "exception - when"
889 argument, and PROPAGATED_EXCEPTION a pointer to the currently propagated
890 occurrence, return true if the latter matches the former, that is, if
891 PROPAGATED_EXCEPTION is caught by the handling code controlled by CHOICE.
894 #define Is_Handled_By_Others __gnat_is_handled_by_others
895 #define Language_For __gnat_language_for
896 #define Foreign_Data_For __gnat_foreign_data_for
897 #define EID_For __gnat_eid_for
899 extern bool Is_Handled_By_Others (_Unwind_Ptr eid
);
900 extern char Language_For (_Unwind_Ptr eid
);
902 extern void *Foreign_Data_For (_Unwind_Ptr eid
);
904 extern Exception_Id
EID_For (_GNAT_Exception
* e
);
906 #define Foreign_Exception system__exceptions__foreign_exception
907 extern struct Exception_Data Foreign_Exception
;
909 /* Return true iff the exception class of EXCEPT is EC. */
912 exception_class_eq (const _GNAT_Exception
*except
,
913 const _Unwind_Exception_Class ec
)
915 #ifdef __ARM_EABI_UNWINDER__
916 return memcmp (except
->common
.exception_class
, ec
, 8) == 0;
918 return except
->common
.exception_class
== ec
;
922 /* Return how CHOICE matches PROPAGATED_EXCEPTION. */
924 static enum action_kind
925 is_handled_by (_Unwind_Ptr choice
, _GNAT_Exception
*propagated_exception
)
927 /* All others choice match everything. */
928 if (choice
== GNAT_ALL_OTHERS
)
931 /* GNAT exception occurrence. */
932 if (exception_class_eq (propagated_exception
, GNAT_EXCEPTION_CLASS
))
934 /* Pointer to the GNAT exception data corresponding to the propagated
936 _Unwind_Ptr E
= (_Unwind_Ptr
) EID_For (propagated_exception
);
938 if (choice
== GNAT_UNHANDLED_OTHERS
)
941 E
= (_Unwind_Ptr
) EID_For (propagated_exception
);
943 /* Base matching rules: An exception data (id) matches itself, "when
944 all_others" matches anything and "when others" matches anything
945 unless explicitly stated otherwise in the propagated occurrence. */
946 if (choice
== E
|| (choice
== GNAT_OTHERS
&& Is_Handled_By_Others (E
)))
949 /* Otherwise, it doesn't match an Ada choice. */
953 /* All others and others choice match any foreign exception. */
954 if (choice
== GNAT_ALL_OTHERS
955 || choice
== GNAT_OTHERS
957 || choice
== (_Unwind_Ptr
) &Foreign_Exception
963 /* C++ exception occurrences. */
964 if (exception_class_eq (propagated_exception
, CXX_EXCEPTION_CLASS
)
965 && Language_For (choice
) == 'C')
967 void *choice_typeinfo
= Foreign_Data_For (choice
);
968 void *except_typeinfo
=
969 (((struct __cxa_exception
*)
970 ((_Unwind_Exception
*)propagated_exception
+ 1)) - 1)
973 /* Typeinfo are directly compared, which might not be correct if they
974 aren't merged. ??? We should call the == operator if this module is
976 if (choice_typeinfo
== except_typeinfo
)
984 /* Fill out the ACTION to be taken from propagating UW_EXCEPTION up to
985 UW_CONTEXT in REGION. */
988 get_action_description_for (_Unwind_Ptr ip
,
989 _Unwind_Exception
*uw_exception
,
990 _Unwind_Action uw_phase
,
991 region_descriptor
*region
,
992 action_descriptor
*action
)
994 _GNAT_Exception
*gnat_exception
= (_GNAT_Exception
*) uw_exception
;
996 /* Search the call site table first, which may get us a landing pad as well
997 as the head of an action record list. */
998 get_call_site_action_for (ip
, region
, action
);
999 db_action_for (action
, ip
);
1001 /* If there is not even a call_site entry, we are done. */
1002 if (action
->kind
== nothing
)
1005 /* Otherwise, check what we have at the place of the call site. */
1007 /* No landing pad => no cleanups or handlers. */
1008 if (action
->landing_pad
== 0)
1010 action
->kind
= nothing
;
1014 /* Landing pad + null table entry => only cleanups. */
1015 else if (action
->table_entry
== 0)
1017 action
->kind
= cleanup
;
1018 action
->ttype_filter
= cleanup_filter
;
1019 /* The filter initialization is not strictly necessary, as cleanup-only
1020 landing pads don't look at the filter value. It is there to ensure
1021 we don't pass random values and so trigger potential confusion when
1022 installing the context later on. */
1026 /* Landing pad + Table entry => handlers + possible cleanups. */
1029 const unsigned char * p
= action
->table_entry
;
1030 _sleb128_t ar_filter
, ar_disp
;
1032 action
->kind
= nothing
;
1036 p
= read_sleb128 (p
, &ar_filter
);
1037 read_sleb128 (p
, &ar_disp
);
1038 /* Don't assign p here, as it will be incremented by ar_disp
1041 /* Null filters are for cleanups. */
1042 if (ar_filter
== cleanup_filter
)
1044 action
->kind
= cleanup
;
1045 action
->ttype_filter
= cleanup_filter
;
1046 /* The filter initialization is required here, to ensure
1047 the target landing pad branches to the cleanup code if
1048 we happen not to find a matching handler. */
1051 /* Positive filters are for regular handlers. */
1052 else if (ar_filter
> 0)
1054 /* Do not catch an exception if the _UA_FORCE_UNWIND flag is
1055 passed (to follow the ABI). */
1056 if (!(uw_phase
& _UA_FORCE_UNWIND
))
1058 enum action_kind act
;
1060 /* See if the filter we have is for an exception which
1061 matches the one we are propagating. */
1062 _Unwind_Ptr choice
=
1063 get_ttype_entry_for (region
, ar_filter
);
1065 act
= is_handled_by (choice
, gnat_exception
);
1069 action
->ttype_filter
= ar_filter
;
1075 /* Negative filter values are for C++ exception specifications.
1076 Should not be there for Ada :/ */
1078 db (DB_ERR
, "========> Err, filter < 0 for Ada/dwarf\n");
1088 /* Setup in UW_CONTEXT the eh return target IP and data registers, which will
1089 be restored with the others and retrieved by the landing pad once the jump
1093 setup_to_install (_Unwind_Context
*uw_context
,
1094 _Unwind_Exception
*uw_exception
,
1095 _Unwind_Ptr uw_landing_pad
,
1098 /* 1/ exception object pointer, which might be provided back to
1099 _Unwind_Resume (and thus to this personality routine) if we are jumping
1101 _Unwind_SetGR (uw_context
, __builtin_eh_return_data_regno (0),
1102 (_Unwind_Word
)uw_exception
);
1104 /* 2/ handler switch value register, which will also be used by the target
1105 landing pad to decide what action it shall take. */
1106 _Unwind_SetGR (uw_context
, __builtin_eh_return_data_regno (1),
1107 (_Unwind_Word
)uw_filter
);
1109 /* Setup the address we should jump at to reach the code where there is the
1110 "something" we found. */
1111 _Unwind_SetIP (uw_context
, uw_landing_pad
);
1114 /* The following is defined from a-except.adb. Its purpose is to enable
1115 automatic backtraces upon exception raise, as provided through the
1116 GNAT.Traceback facilities. */
1117 extern void __gnat_notify_handled_exception (struct Exception_Occurrence
*);
1118 extern void __gnat_notify_unhandled_exception (struct Exception_Occurrence
*);
1120 /* Below is the eh personality routine per se. We currently assume that only
1121 GNU-Ada exceptions are met. */
1123 /* By default, the personality routine is public. */
1124 #define PERSONALITY_STORAGE
1126 #ifdef __USING_SJLJ_EXCEPTIONS__
1127 #define PERSONALITY_FUNCTION __gnat_personality_sj0
1128 #elif defined (__SEH__)
1129 #define PERSONALITY_FUNCTION __gnat_personality_imp
1130 /* The public personality routine for seh is __gnat_personality_seh0, defined
1131 below using the SEH convention. This is a wrapper around the GNU routine,
1133 #undef PERSONALITY_STORAGE
1134 #define PERSONALITY_STORAGE static
1136 #define PERSONALITY_FUNCTION __gnat_personality_v0
1139 #if defined (__ARM_EABI_UNWINDER__) \
1140 && (defined (IN_RTS) || GCC_VERSION > 9000)
1141 #define TARGET_ATTRIBUTE __attribute__((target ("general-regs-only")))
1143 #define TARGET_ATTRIBUTE
1146 /* Code executed to continue unwinding. With the ARM unwinder, the
1147 personality routine must unwind one frame (per EHABI 7.3 4.). */
1149 static _Unwind_Reason_Code
1151 continue_unwind (struct _Unwind_Exception
* ue_header ATTRIBUTE_UNUSED
,
1152 struct _Unwind_Context
* uw_context ATTRIBUTE_UNUSED
)
1154 #ifdef __ARM_EABI_UNWINDER__
1155 if (__gnu_unwind_frame (ue_header
, uw_context
) != _URC_OK
)
1156 return _URC_FAILURE
;
1158 return _URC_CONTINUE_UNWIND
;
1161 /* Common code for the body of GNAT personality routine. This code is shared
1162 between all unwinders. */
1164 static _Unwind_Reason_Code
1166 personality_body (_Unwind_Action uw_phases
,
1167 _Unwind_Exception
*uw_exception
,
1168 _Unwind_Context
*uw_context
)
1170 region_descriptor region
;
1171 action_descriptor action
;
1175 db_indent (DB_INDENT_RESET
);
1176 db_phases (uw_phases
);
1177 db_indent (DB_INDENT_INCREASE
);
1179 /* Get the region description for the context we were provided with. This
1180 will tell us if there is some lsda, call_site, action and/or ttype data
1181 for the associated ip. */
1182 get_region_description_for (uw_context
, ®ion
);
1184 /* No LSDA => no handlers or cleanups => we shall unwind further up. */
1186 return continue_unwind (uw_exception
, uw_context
);
1188 /* Get the instruction pointer. */
1189 ip
= get_ip_from_context (uw_context
);
1190 db_region_for (®ion
, ip
);
1192 /* Search the call-site and action-record tables for the action associated
1194 get_action_description_for (ip
, uw_exception
, uw_phases
, ®ion
, &action
);
1195 db_action_for (&action
, ip
);
1197 /* Whatever the phase, if there is nothing relevant in this frame,
1198 unwinding should just go on. */
1199 if (action
.kind
== nothing
)
1200 return continue_unwind (uw_exception
, uw_context
);
1202 /* If we found something in search phase, we should return a code indicating
1203 what to do next depending on what we found. If we only have cleanups
1204 around, we shall try to unwind further up to find a handler, otherwise,
1205 tell we have a handler, which will trigger the second phase. */
1206 if (uw_phases
& _UA_SEARCH_PHASE
)
1208 if (action
.kind
== cleanup
)
1210 return continue_unwind (uw_exception
, uw_context
);
1215 /* Trigger the appropriate notification routines before the second
1216 phase starts, when the stack is still intact. First install what
1217 needs to be installed in the current exception buffer and fetch
1218 the Ada occurrence pointer to use. */
1220 struct Exception_Occurrence
*excep
1221 = __gnat_setup_current_excep (uw_exception
, uw_phases
);
1223 if (action
.kind
== unhandler
)
1224 __gnat_notify_unhandled_exception (excep
);
1226 __gnat_notify_handled_exception (excep
);
1229 return _URC_HANDLER_FOUND
;
1233 /* We found something in cleanup/handler phase, which might be the handler
1234 or a cleanup for a handled occurrence, or a cleanup for an unhandled
1235 occurrence (we are in a FORCED_UNWIND phase in this case). Install the
1236 context to get there. */
1239 (uw_context
, uw_exception
, action
.landing_pad
, action
.ttype_filter
);
1242 /* Write current exception so that it can be retrieved from Ada. It was
1243 already done during phase 1, but one or several exceptions may have been
1244 raised in cleanup handlers in between. */
1245 __gnat_setup_current_excep (uw_exception
, uw_phases
);
1248 return _URC_INSTALL_CONTEXT
;
1251 #ifndef __ARM_EABI_UNWINDER__
1252 typedef int version_arg_t
;
1253 typedef _Unwind_Action phases_arg_t
;
1255 PERSONALITY_STORAGE _Unwind_Reason_Code
1256 PERSONALITY_FUNCTION (version_arg_t
, phases_arg_t
,
1257 _Unwind_Exception_Class
, _Unwind_Exception
*,
1260 PERSONALITY_STORAGE _Unwind_Reason_Code
1261 PERSONALITY_FUNCTION (version_arg_t version_arg
,
1262 phases_arg_t phases_arg
,
1263 _Unwind_Exception_Class uw_exception_class
1265 _Unwind_Exception
*uw_exception
,
1266 _Unwind_Context
*uw_context
)
1268 /* Fetch the version and phases args with their nominal ABI types for later
1269 use. This is a noop everywhere except on ia64-vms when called from the
1270 Condition Handling Facility. */
1271 int uw_version
= (int) version_arg
;
1272 _Unwind_Action uw_phases
= (_Unwind_Action
) phases_arg
;
1274 /* Check that we're called from the ABI context we expect. */
1275 if (uw_version
!= 1)
1276 return _URC_FATAL_PHASE1_ERROR
;
1278 return personality_body (uw_phases
, uw_exception
, uw_context
);
1281 #else /* __ARM_EABI_UNWINDER__ */
1283 PERSONALITY_STORAGE _Unwind_Reason_Code
1284 PERSONALITY_FUNCTION (_Unwind_State state
,
1285 struct _Unwind_Exception
* ue_header
,
1286 struct _Unwind_Context
* uw_context
);
1288 PERSONALITY_STORAGE _Unwind_Reason_Code
1290 PERSONALITY_FUNCTION (_Unwind_State state
,
1291 struct _Unwind_Exception
* uw_exception
,
1292 struct _Unwind_Context
* uw_context
)
1294 _Unwind_Action uw_phases
;
1296 switch (state
& _US_ACTION_MASK
)
1298 case _US_VIRTUAL_UNWIND_FRAME
:
1300 uw_phases
= _UA_SEARCH_PHASE
;
1303 case _US_UNWIND_FRAME_STARTING
:
1304 /* Phase 2, to call a cleanup. */
1305 uw_phases
= _UA_CLEANUP_PHASE
;
1307 /* ??? We don't use UA_HANDLER_FRAME (except to debug). Futhermore,
1308 barrier_cache.sp isn't yet set. */
1309 if (!(state
& _US_FORCE_UNWIND
)
1310 && (uw_exception
->barrier_cache
.sp
1311 == _Unwind_GetGR (uw_context
, UNWIND_STACK_REG
)))
1312 uw_phases
|= _UA_HANDLER_FRAME
;
1316 case _US_UNWIND_FRAME_RESUME
:
1317 /* Phase 2, called at the return of a cleanup. In the GNU
1318 implementation, there is nothing left to do, so we simply go on. */
1319 return continue_unwind (uw_exception
, uw_context
);
1322 return _URC_FAILURE
;
1324 uw_phases
|= (state
& _US_FORCE_UNWIND
);
1326 /* The dwarf unwinder assumes the context structure holds things like the
1327 function and LSDA pointers. The ARM implementation caches these in
1328 the exception header (UCB). To avoid rewriting everything we make a
1329 virtual scratch register point at the UCB. This is a GNU specific
1331 _Unwind_SetGR (uw_context
, UNWIND_POINTER_REG
, (_Unwind_Ptr
) uw_exception
);
1333 return personality_body (uw_phases
, uw_exception
, uw_context
);
1335 #endif /* __ARM_EABI_UNWINDER__ */
1337 /* Callback routine called by Unwind_ForcedUnwind to execute all the cleanup
1338 before exiting the task. */
1342 __gnat_cleanupunwind_handler (int version ATTRIBUTE_UNUSED
,
1343 _Unwind_Action phases
,
1344 _Unwind_Exception_Class eclass ATTRIBUTE_UNUSED
,
1345 struct _Unwind_Exception
*exception
,
1346 struct _Unwind_Context
*context ATTRIBUTE_UNUSED
,
1347 void *arg ATTRIBUTE_UNUSED
)
1349 /* Terminate when the end of the stack is reached. */
1350 if ((phases
& _UA_END_OF_STACK
) != 0
1351 #if defined (__ia64__) && defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
1352 /* Strictely follow the ia64 ABI: when end of stack is reached,
1353 the callback will be called with a NULL stack pointer.
1354 No need for that when using libgcc unwinder. */
1355 || _Unwind_GetGR (context
, 12) == 0
1358 __gnat_unhandled_except_handler (exception
);
1360 /* We know there is at least one cleanup further up. Return so that it
1361 is searched and entered, after which Unwind_Resume will be called
1362 and this hook will gain control again. */
1363 return _URC_NO_REASON
;
1367 /* Define the consistently named wrappers imported by Propagate_Exception. */
1370 __gnat_Unwind_RaiseException (_Unwind_Exception
*e
)
1372 #ifdef __USING_SJLJ_EXCEPTIONS__
1373 return _Unwind_SjLj_RaiseException (e
);
1375 return _Unwind_RaiseException (e
);
1380 __gnat_Unwind_ForcedUnwind (_Unwind_Exception
*e ATTRIBUTE_UNUSED
,
1381 _Unwind_Stop_Fn handler ATTRIBUTE_UNUSED
,
1382 void *argument ATTRIBUTE_UNUSED
)
1384 #ifdef __USING_SJLJ_EXCEPTIONS__
1386 # if defined (__APPLE__) && defined (__arm__)
1387 /* There is not ForcedUnwind routine in arm-darwin system library. */
1388 return _URC_FATAL_PHASE1_ERROR
;
1390 return _Unwind_SjLj_ForcedUnwind (e
, handler
, argument
);
1394 return _Unwind_ForcedUnwind (e
, handler
, argument
);
1398 #if defined (__SEH__) && !defined (__USING_SJLJ_EXCEPTIONS__)
1400 #define STATUS_USER_DEFINED (1U << 29)
1402 /* From unwind-seh.c. */
1403 #define GCC_MAGIC (('G' << 16) | ('C' << 8) | 'C')
1404 #define GCC_EXCEPTION(TYPE) \
1405 (STATUS_USER_DEFINED | ((TYPE) << 24) | GCC_MAGIC)
1406 #define STATUS_GCC_THROW GCC_EXCEPTION (0)
1408 struct Exception_Data
*
1409 __gnat_map_SEH (EXCEPTION_RECORD
* ExceptionRecord
, const char **msg
);
1411 struct _Unwind_Exception
*
1412 __gnat_create_machine_occurrence_from_signal_handler (Exception_Id
,
1415 /* Unwind opcodes. */
1416 #define UWOP_PUSH_NONVOL 0
1417 #define UWOP_ALLOC_LARGE 1
1418 #define UWOP_ALLOC_SMALL 2
1419 #define UWOP_SET_FPREG 3
1420 #define UWOP_SAVE_NONVOL 4
1421 #define UWOP_SAVE_NONVOL_FAR 5
1422 #define UWOP_SAVE_XMM128 8
1423 #define UWOP_SAVE_XMM128_FAR 9
1424 #define UWOP_PUSH_MACHFRAME 10
1426 /* Modify the IP value saved in the machine frame. This is really a kludge,
1427 that will be removed if we could propagate the Windows exception (and not
1430 What is very wrong is that the Windows unwinder will try to decode the
1431 instruction at IP, which isn't valid anymore after the adjustment. */
1434 __gnat_adjust_context (unsigned char *unw
, ULONG64 rsp
)
1438 /* Version 1 or 2. */
1439 if (unw
[0] != 1 && unw
[0] != 2)
1441 /* No flags, no prologue. */
1448 /* ??? Skip the first 2 undocumented opcodes for version 2. */
1455 /* Offset in prologue = 0. */
1458 switch (unw
[1] & 0xf)
1460 case UWOP_ALLOC_LARGE
:
1461 /* Expect < 512KB. */
1462 if ((unw
[1] & 0xf0) != 0)
1464 rsp
+= *(unsigned short *)(unw
+ 2) * 8;
1468 case UWOP_SAVE_NONVOL
:
1469 case UWOP_SAVE_XMM128
:
1473 case UWOP_PUSH_MACHFRAME
:
1476 rip
= (ULONG64
*)rsp
;
1477 if ((unw
[1] & 0xf0) == 0x10)
1492 EXCEPTION_DISPOSITION
1493 __gnat_personality_seh0 (PEXCEPTION_RECORD ms_exc
, void *this_frame
,
1494 PCONTEXT ms_orig_context
,
1495 PDISPATCHER_CONTEXT ms_disp
)
1497 /* Possibly transform run-time errors into Ada exceptions. */
1498 if (!(ms_exc
->ExceptionCode
& STATUS_USER_DEFINED
))
1500 struct Exception_Data
*exception
;
1502 ULONG64 excpip
= (ULONG64
) ms_exc
->ExceptionAddress
;
1505 && excpip
>= (ms_disp
->ImageBase
1506 + ms_disp
->FunctionEntry
->BeginAddress
)
1507 && excpip
< (ms_disp
->ImageBase
1508 + ms_disp
->FunctionEntry
->EndAddress
))
1510 /* This is a fault in this function. We need to adjust the return
1511 address before raising the GCC exception. In order to do that,
1512 we need to locate the machine frame that has been pushed onto
1513 the stack in response to the hardware exception, so we will do
1514 a private unwinding from here, i.e. the frame of the personality
1515 routine, up to the frame immediately following the frame of this
1516 function. This frame corresponds to a dummy prologue which is
1517 never actually executed but instead appears before the real entry
1518 point of an interrupt routine and exists only to provide a place
1519 to simulate the push of a machine frame. */
1521 PRUNTIME_FUNCTION mf_func
= NULL
;
1522 ULONG64 mf_imagebase
;
1525 /* Get the current context. */
1526 RtlCaptureContext (&context
);
1530 PRUNTIME_FUNCTION RuntimeFunction
;
1533 ULONG64 EstablisherFrame
;
1535 /* Get function metadata. */
1537 = RtlLookupFunctionEntry (context
.Rip
, &ImageBase
,
1538 ms_disp
->HistoryTable
);
1540 /* Stop once we reached the frame of this function. */
1541 if (RuntimeFunction
== ms_disp
->FunctionEntry
)
1544 mf_func
= RuntimeFunction
;
1545 mf_imagebase
= ImageBase
;
1546 mf_rsp
= context
.Rsp
;
1548 if (RuntimeFunction
)
1551 RtlVirtualUnwind (0, ImageBase
, context
.Rip
, RuntimeFunction
,
1552 &context
, &HandlerData
, &EstablisherFrame
,
1557 /* In case of failure, assume this is a leaf function. */
1558 context
.Rip
= *(ULONG64
*) context
.Rsp
;
1562 /* 0 means bottom of the stack. */
1563 if (context
.Rip
== 0)
1570 /* If we have found the machine frame, adjust the return address. */
1571 if (mf_func
!= NULL
)
1572 __gnat_adjust_context
1573 ((unsigned char *)(mf_imagebase
+ mf_func
->UnwindData
), mf_rsp
);
1576 exception
= __gnat_map_SEH (ms_exc
, &msg
);
1577 if (exception
!= NULL
)
1579 /* Directly convert the system exception into a GCC one.
1581 This is really breaking the API, but is necessary for stack size
1582 reasons: the normal way is to call Raise_From_Signal_Handler,
1583 which builds the exception and calls _Unwind_RaiseException,
1584 which unwinds the stack and will call this personality routine.
1585 But the Windows unwinder needs about 2KB of stack. */
1586 struct _Unwind_Exception
*exc
1587 = __gnat_create_machine_occurrence_from_signal_handler (exception
,
1589 memset (exc
->private_
, 0, sizeof (exc
->private_
));
1590 ms_exc
->ExceptionCode
= STATUS_GCC_THROW
;
1591 ms_exc
->NumberParameters
= 1;
1592 ms_exc
->ExceptionInformation
[0] = (ULONG_PTR
)exc
;
1598 _GCC_specific_handler (ms_exc
, this_frame
, ms_orig_context
, ms_disp
,
1599 __gnat_personality_imp
);
1602 /* Define __gnat_personality_v0 for convenience */
1604 PERSONALITY_STORAGE _Unwind_Reason_Code
1605 __gnat_personality_v0 (version_arg_t version_arg
,
1606 phases_arg_t phases_arg
,
1607 _Unwind_Exception_Class uw_exception_class
,
1608 _Unwind_Exception
*uw_exception
,
1609 _Unwind_Context
*uw_context
)
1611 return PERSONALITY_FUNCTION
1612 (version_arg
, phases_arg
, uw_exception_class
, uw_exception
, uw_context
);
1617 #if !defined (__USING_SJLJ_EXCEPTIONS__)
1618 /* Size of the _Unwind_Exception structure. This is used by g-cppexc to get
1619 the offset to the C++ object. */
1621 const int __gnat_unwind_exception_size
= sizeof (_Unwind_Exception
);