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-2019, 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  ****************************************************************************/
31 
32 /* Code related to the integration of the GCC mechanism for exception
33    handling.  */
34 
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 # ifndef CERT
43 #  include "tconfig.h"
44 #  include "tsystem.h"
45 # else
46 #  define ATTRIBUTE_UNUSED __attribute__((unused))
47 #  define HAVE_GETIPINFO 1
48 # endif
49 #endif
50 
51 #include <stdarg.h>
52 
53 #ifdef __cplusplus
54 # include <cstdlib>
55 #else
56 typedef char bool;
57 # define true 1
58 # define false 0
59 #endif
60 
61 #include "raise.h"
62 
63 #ifdef __APPLE__
64 /* On MacOS X, versions older than 10.5 don't export _Unwind_GetIPInfo.  */
65 #undef HAVE_GETIPINFO
66 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
67 #define HAVE_GETIPINFO 1
68 #endif
69 #endif
70 
71 #if defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
72 /* HP-UX B.11.31 ia64 libunwind doesn't have _Unwind_GetIPInfo. */
73 #undef HAVE_GETIPINFO
74 #define _UA_END_OF_STACK 0
75 #endif
76 
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.  */
81 
82 #ifdef __CYGWIN__
83 /* Prevent compile error due to unwind-generic.h including <windows.h>,
84    see comment above #include <windows.h> in mingw32.h.  */
85 #include "mingw32.h"
86 #endif
87 
88 #ifndef IN_RTS
89   /* For gnat1/gnatbind compilation: cannot use unwind.h, as it is for the
90      target. So mimic configure...
91      This is a hack ???, the real fix is to link gnat1/gnatbind with the
92      runtime of the build compiler.  */
93 # ifdef EH_MECHANISM_arm
94 #   include "config/arm/unwind-arm.h"
95 # else
96 #   include "unwind-generic.h"
97 # endif
98 #else
99 # include "unwind.h"
100 #endif
101 
102 #ifdef __cplusplus
103 extern "C" {
104 #endif
105 
106 typedef struct _Unwind_Context _Unwind_Context;
107 typedef struct _Unwind_Exception _Unwind_Exception;
108 
109 _Unwind_Reason_Code
110 __gnat_Unwind_RaiseException (_Unwind_Exception *);
111 
112 _Unwind_Reason_Code
113 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *, _Unwind_Stop_Fn, void *);
114 
115 extern struct Exception_Occurrence *
116 __gnat_setup_current_excep (_Unwind_Exception *, _Unwind_Action);
117 
118 extern void __gnat_unhandled_except_handler (_Unwind_Exception *);
119 
120 #ifdef CERT
121 /* Called in case of error during propagation.  */
122 extern void __gnat_raise_abort (void) __attribute__ ((noreturn));
123 #define abort() __gnat_raise_abort()
124 #endif
125 
126 #include "unwind-pe.h"
127 
128 #ifdef __ARM_EABI_UNWINDER__
129 /* for memcmp */
130 #include <string.h>
131 #endif
132 
133 /* The known and handled exception classes.  */
134 
135 #ifdef __ARM_EABI_UNWINDER__
136 #define CXX_EXCEPTION_CLASS "GNUCC++"
137 #define GNAT_EXCEPTION_CLASS "GNU-Ada"
138 #else
139 #define CXX_EXCEPTION_CLASS 0x474e5543432b2b00ULL
140 #define GNAT_EXCEPTION_CLASS 0x474e552d41646100ULL
141 #endif
142 
143 /* Structure of a C++ exception, represented as a C structure...  See
144    unwind-cxx.h for the full definition.  */
145 
146 struct __cxa_exception
147 {
148   void *exceptionType;
149   void (*exceptionDestructor)(void *);
150 
151   void (*unexpectedHandler)();
152   void (*terminateHandler)();
153 
154   struct __cxa_exception *nextException;
155 
156   int handlerCount;
157 
158 #ifdef __ARM_EABI_UNWINDER__
159   struct __cxa_exception* nextPropagatingException;
160 
161   int propagationCount;
162 #else
163   int handlerSwitchValue;
164   const unsigned char *actionRecord;
165   const unsigned char *languageSpecificData;
166   _Unwind_Ptr catchTemp;
167   void *adjustedPtr;
168 #endif
169 
170   _Unwind_Exception unwindHeader;
171 };
172 
173 /* --------------------------------------------------------------
174    -- The DB stuff below is there for debugging purposes only. --
175    -------------------------------------------------------------- */
176 
177 #ifndef inhibit_libc
178 
179 #define DB_PHASES     0x1
180 #define DB_CSITE      0x2
181 #define DB_ACTIONS    0x4
182 #define DB_REGIONS    0x8
183 
184 #define DB_ERR        0x1000
185 
186 /* The "action" stuff below is also there for debugging purposes only.  */
187 
188 typedef struct
189 {
190   _Unwind_Action phase;
191   const char * description;
192 } phase_descriptor;
193 
194 static const phase_descriptor phase_descriptors[]
195   = {{ _UA_SEARCH_PHASE,  "SEARCH_PHASE" },
196      { _UA_CLEANUP_PHASE, "CLEANUP_PHASE" },
197      { _UA_HANDLER_FRAME, "HANDLER_FRAME" },
198      { _UA_FORCE_UNWIND,  "FORCE_UNWIND" },
199      { -1, 0}};
200 
201 static int
db_accepted_codes(void)202 db_accepted_codes (void)
203 {
204   static int accepted_codes = -1;
205 
206   if (accepted_codes == -1)
207     {
208       char * db_env = (char *) getenv ("EH_DEBUG");
209 
210       accepted_codes = db_env ? (atoi (db_env) | DB_ERR) : 0;
211       /* Arranged for ERR stuff to always be visible when the variable
212 	 is defined. One may just set the variable to 0 to see the ERR
213 	 stuff only.  */
214     }
215 
216   return accepted_codes;
217 }
218 
219 #define DB_INDENT_INCREASE 0x01
220 #define DB_INDENT_DECREASE 0x02
221 #define DB_INDENT_OUTPUT   0x04
222 #define DB_INDENT_NEWLINE  0x08
223 #define DB_INDENT_RESET    0x10
224 
225 #define DB_INDENT_UNIT     8
226 
227 static void
db_indent(int requests)228 db_indent (int requests)
229 {
230   static int current_indentation_level = 0;
231 
232   if (requests & DB_INDENT_RESET)
233     current_indentation_level = 0;
234 
235   if (requests & DB_INDENT_INCREASE)
236     current_indentation_level ++;
237 
238   if (requests & DB_INDENT_DECREASE)
239     current_indentation_level --;
240 
241   if (requests & DB_INDENT_NEWLINE)
242     fprintf (stderr, "\n");
243 
244   if (requests & DB_INDENT_OUTPUT)
245     fprintf (stderr, "%*s", current_indentation_level * DB_INDENT_UNIT, " ");
246 }
247 
248 static void ATTRIBUTE_PRINTF_2
db(int db_code,const char * msg_format,...)249 db (int db_code, const char * msg_format, ...)
250 {
251   if (db_accepted_codes () & db_code)
252     {
253       va_list msg_args;
254 
255       db_indent (DB_INDENT_OUTPUT);
256 
257       va_start (msg_args, msg_format);
258       vfprintf (stderr, msg_format, msg_args);
259       va_end (msg_args);
260     }
261 }
262 
263 static void
db_phases(int phases)264 db_phases (int phases)
265 {
266   const phase_descriptor *a = phase_descriptors;
267 
268   if (! (db_accepted_codes () & DB_PHASES))
269     return;
270 
271   db (DB_PHASES, "\n");
272 
273   for (; a->description != 0; a++)
274     if (phases & a->phase)
275       db (DB_PHASES, "%s ", a->description);
276 
277   db (DB_PHASES, " :\n");
278 }
279 #else /* !inhibit_libc */
280 #define db_phases(X)
281 #define db_indent(X)
282 #define db(X, ...)
283 #endif /* !inhibit_libc */
284 
285 /* ---------------------------------------------------------------
286    --  Now come a set of useful structures and helper routines. --
287    --------------------------------------------------------------- */
288 
289 /* There are three major runtime tables involved, generated by the
290    GCC back-end. Contents slightly vary depending on the underlying
291    implementation scheme (dwarf zero cost / sjlj).
292 
293    =======================================
294    * Tables for the dwarf zero cost case *
295    =======================================
296 
297    They are fully documented in:
298      http://sourcery.mentor.com/public/cxx-abi/exceptions.pdf
299    Here is a shorter presentation, with some specific comments for Ada.
300 
301    call_site []
302    -------------------------------------------------------------------
303    * region-start | region-length | landing-pad | first-action-index *
304    -------------------------------------------------------------------
305 
306    Identify possible actions to be taken and where to resume control
307    for that when an exception propagates through a pc inside the region
308    delimited by start and length.
309 
310    A null landing-pad indicates that nothing is to be done.
311 
312    Otherwise, first-action-index provides an entry into the action[]
313    table which heads a list of possible actions to be taken (see below).
314 
315    If it is determined that indeed an action should be taken, that
316    is, if one action filter matches the exception being propagated,
317    then control should be transferred to landing-pad.
318 
319    A null first-action-index indicates that there are only cleanups
320    to run there.
321 
322    action []
323    -------------------------------
324    * action-filter | next-action *
325    -------------------------------
326 
327    This table contains lists (called action chains) of possible actions
328    associated with call-site entries described in the call-site [] table.
329    There is at most one action list per call-site entry.  It is SLEB128
330    encoded.
331 
332    A null action-filter indicates a cleanup.
333 
334    Non null action-filters provide an index into the ttypes [] table
335    (see below), from which information may be retrieved to check if it
336    matches the exception being propagated.
337 
338    * action-filter > 0:
339    means there is a regular handler to be run The value is also passed
340    to the landing pad to dispatch the exception.
341 
342    * action-filter < 0:
343    means there is a some "exception_specification" data to retrieve,
344    which is only relevant for C++ and should never show up for Ada.
345    (Exception specification specifies which exceptions can be thrown
346    by a function. Such filter is emitted around the body of C++
347    functions defined like:
348      void foo ([...])  throw (A, B) { [...] }
349    These can be viewed as negativ filter: the landing pad is branched
350    to for exceptions that doesn't match the filter and usually aborts
351    the program).
352 
353    * next-action
354    points to the next entry in the list using a relative byte offset. 0
355    indicates there is no other entry.
356 
357    ttypes []
358    ---------------
359    * ttype-value *
360    ---------------
361 
362    This table is an array of addresses.
363 
364    A null value indicates a catch-all handler.  (Not used by Ada)
365 
366    Non null values are used to match the exception being propagated:
367    In C++ this is a pointer to some rtti data, while in Ada this is an
368    exception id (with a fake id for others).
369 
370    For C++, this table is actually also used to store "exception
371    specification" data. The differentiation between the two kinds
372    of entries is made by the sign of the associated action filter,
373    which translates into positive or negative offsets from the
374    so called base of the table:
375 
376    Exception Specification data is stored at positive offsets from
377    the ttypes table base, which Exception Type data is stored at
378    negative offsets:
379 
380    ---------------------------------------------------------------------------
381 
382    Here is a quick summary of the tables organization:
383 
384 	  +-- Unwind_Context (pc, ...)
385 	  |
386 	  |(pc)
387 	  |
388 	  |   CALL-SITE[]
389 	  |
390 	  |   +=============================================================+
391 	  |   | region-start + length |  landing-pad   | first-action-index |
392 	  |   +=============================================================+
393 	  +-> |       pc range          0 => no-action   0 => cleanups only |
394 	      |                         !0 => jump @              N --+     |
395 	      +====================================================== | ====+
396                                                                       |
397                                                                       |
398        ACTION []                                                      |
399                                                                       |
400        +==========================================================+   |
401        |              action-filter           |   next-action     |   |
402        +==========================================================+   |
403        |  0 => cleanup                                            |   |
404        | >0 => ttype index for handler ------+  0 => end of chain | <-+
405        | <0 => ttype index for spec data     |                    |
406        +==================================== | ===================+
407                                              |
408                                              |
409        TTYPES []                             |
410 					     |  Offset negated from
411 		 +=====================+     |  the actual base.
412 		 |     ttype-value     |     |
413     +============+=====================+     |
414     |            |        ...          |     |
415     |    ...     |     exception id    | <---+
416     |            |        ...          |
417     |  handlers	 +---------------------+
418     |            |        ...          |
419     |    ...     |        ...          |
420     |            |        ...          |
421     +============+=====================+ <<------ Table base
422     |    ...     |        ...          |
423     |   specs    |        ...          | (should not see negative filter
424     |    ...     |        ...          |  values for Ada).
425     +============+=====================+
426 
427 
428    ============================
429    * Tables for the sjlj case *
430    ============================
431 
432    So called "function contexts" are pushed on a context stack by calls to
433    _Unwind_SjLj_Register on function entry, and popped off at exit points by
434    calls to _Unwind_SjLj_Unregister. The current call_site for a function is
435    updated in the function context as the function's code runs along.
436 
437    The generic unwinding engine in _Unwind_RaiseException walks the function
438    context stack and not the actual call chain.
439 
440    The ACTION and TTYPES tables remain unchanged, which allows to search them
441    during the propagation phase to determine whether or not the propagated
442    exception is handled somewhere. When it is, we only "jump" up once directly
443    to the context where the handler will be found. Besides, this allows "break
444    exception unhandled" to work also
445 
446    The CALL-SITE table is setup differently, though: the pc attached to the
447    unwind context is a direct index into the table, so the entries in this
448    table do not hold region bounds any more.
449 
450    A special index (-1) is used to indicate that no action is possibly
451    connected with the context at hand, so null landing pads cannot appear
452    in the table.
453 
454    Additionally, landing pad values in the table do not represent code address
455    to jump at, but so called "dispatch" indices used by a common landing pad
456    for the function to switch to the appropriate post-landing-pad.
457 
458    +-- Unwind_Context (pc, ...)
459    |
460    | pc = call-site index
461    |  0 => terminate (should not see this for Ada)
462    | -1 => no-action
463    |
464    |   CALL-SITE[]
465    |
466    |   +=====================================+
467    |   |  landing-pad   | first-action-index |
468    |   +=====================================+
469    +-> |                  0 => cleanups only |
470        | dispatch index             N        |
471        +=====================================+
472 
473 
474    ===================================
475    * Basic organization of this unit *
476    ===================================
477 
478    The major point of this unit is to provide an exception propagation
479    personality routine for Ada. This is __gnat_personality_v0.
480 
481    It is provided with a pointer to the propagated exception, an unwind
482    context describing a location the propagation is going through, and a
483    couple of other arguments including a description of the current
484    propagation phase.
485 
486    It shall return to the generic propagation engine what is to be performed
487    next, after possible context adjustments, depending on what it finds in the
488    traversed context (a handler for the exception, a cleanup, nothing, ...),
489    and on the propagation phase.
490 
491    A number of structures and subroutines are used for this purpose, as
492    sketched below:
493 
494    o region_descriptor: General data associated with the context (base pc,
495      call-site table, action table, ttypes table, ...)
496 
497    o action_descriptor: Data describing the action to be taken for the
498      propagated exception in the provided context (kind of action: nothing,
499      handler, cleanup; pointer to the action table entry, ...).
500 
501    raise
502      |
503     ... (a-except.adb)
504      |
505    Propagate_Exception (a-exexpr.adb)
506      |
507      |
508    _Unwind_RaiseException (libgcc)
509      |
510      |   (Ada frame)
511      |
512      +--> __gnat_personality_v0 (context, exception)
513 	   |
514 	   +--> get_region_description_for (context)
515 	   |
516 	   +--> get_action_description_for (ip, exception, region)
517 	   |       |
518 	   |       +--> get_call_site_action_for (context, region)
519 	   |            (one version for each underlying scheme)
520            |
521 	   +--> setup_to_install (context)
522 
523    This unit is inspired from the C++ version found in eh_personality.cc,
524    part of libstdc++-v3.
525 
526 */
527 
528 
529 /* This is an incomplete "proxy" of the structure of exception objects as
530    built by the GNAT runtime library. Accesses to other fields than the common
531    header are performed through subprogram calls to alleviate the need of an
532    exact counterpart here and potential alignment/size issues for the common
533    header. See a-exexpr.adb.  */
534 
535 typedef struct
536 {
537   _Unwind_Exception common;
538   /* ABI header, maximally aligned. */
539 } _GNAT_Exception;
540 
541 /* The two constants below are specific ttype identifiers for special
542    exception ids.  Their type should match what a-exexpr exports.  */
543 
544 extern const int __gnat_others_value;
545 #define GNAT_OTHERS      ((_Unwind_Ptr) &__gnat_others_value)
546 
547 extern const int __gnat_all_others_value;
548 #define GNAT_ALL_OTHERS  ((_Unwind_Ptr) &__gnat_all_others_value)
549 
550 extern const int __gnat_unhandled_others_value;
551 #define GNAT_UNHANDLED_OTHERS  ((_Unwind_Ptr) &__gnat_unhandled_others_value)
552 
553 /* Describe the useful region data associated with an unwind context.  */
554 
555 typedef struct
556 {
557   /* The base pc of the region.  */
558   _Unwind_Ptr base;
559 
560   /* Pointer to the Language Specific Data for the region.  */
561   _Unwind_Ptr lsda;
562 
563   /* Call-Site data associated with this region.  */
564   unsigned char call_site_encoding;
565   const unsigned char *call_site_table;
566 
567   /* The base to which are relative landing pad offsets inside the call-site
568      entries .  */
569   _Unwind_Ptr lp_base;
570 
571   /* Action-Table associated with this region.  */
572   const unsigned char *action_table;
573 
574   /* Ttype data associated with this region.  */
575   unsigned char ttype_encoding;
576   const unsigned char *ttype_table;
577   _Unwind_Ptr ttype_base;
578 
579 } region_descriptor;
580 
581 /* Extract and adjust the IP (instruction pointer) from an exception
582    context.  */
583 
584 static _Unwind_Ptr
get_ip_from_context(_Unwind_Context * uw_context)585 get_ip_from_context (_Unwind_Context *uw_context)
586 {
587   int ip_before_insn = 0;
588 #ifdef HAVE_GETIPINFO
589   _Unwind_Ptr ip = _Unwind_GetIPInfo (uw_context, &ip_before_insn);
590 #else
591   _Unwind_Ptr ip = _Unwind_GetIP (uw_context);
592 #endif
593   /* Subtract 1 if necessary because GetIPInfo yields a call return address
594      in this case, while we are interested in information for the call point.
595      This does not always yield the exact call instruction address but always
596      brings the IP back within the corresponding region.  */
597   if (!ip_before_insn)
598     ip--;
599 
600   return ip;
601 }
602 
603 static void
db_region_for(region_descriptor * region,_Unwind_Ptr ip)604 db_region_for (region_descriptor *region, _Unwind_Ptr ip)
605 {
606 #ifndef inhibit_libc
607   if (! (db_accepted_codes () & DB_REGIONS))
608     return;
609 
610   db (DB_REGIONS, "For ip @ %p => ", (void *)ip);
611 
612   if (region->lsda)
613     db (DB_REGIONS, "lsda @ %p", (void *)region->lsda);
614   else
615     db (DB_REGIONS, "no lsda");
616 
617   db (DB_REGIONS, "\n");
618 #endif
619 }
620 
621 /* Retrieve the ttype entry associated with FILTER in the REGION's
622    ttype table.  */
623 
624 static _Unwind_Ptr
get_ttype_entry_for(region_descriptor * region,long filter)625 get_ttype_entry_for (region_descriptor *region, long filter)
626 {
627   _Unwind_Ptr ttype_entry;
628 
629   filter *= size_of_encoded_value (region->ttype_encoding);
630   read_encoded_value_with_base
631     (region->ttype_encoding, region->ttype_base,
632      region->ttype_table - filter, &ttype_entry);
633 
634   return ttype_entry;
635 }
636 
637 /* Fill out the REGION descriptor for the provided UW_CONTEXT.  */
638 
639 static void
get_region_description_for(_Unwind_Context * uw_context,region_descriptor * region)640 get_region_description_for (_Unwind_Context *uw_context,
641                             region_descriptor *region)
642 {
643   const unsigned char * p;
644   _uleb128_t tmp;
645   unsigned char lpbase_encoding;
646 
647   /* Get the base address of the lsda information. If the provided context
648      is null or if there is no associated language specific data, there's
649      nothing we can/should do.  */
650   region->lsda
651     = (_Unwind_Ptr) (uw_context
652 		     ? _Unwind_GetLanguageSpecificData (uw_context) : 0);
653 
654   if (! region->lsda)
655     return;
656 
657   /* Parse the lsda and fill the region descriptor.  */
658   p = (const unsigned char *)region->lsda;
659 
660   region->base = _Unwind_GetRegionStart (uw_context);
661 
662   /* Find @LPStart, the base to which landing pad offsets are relative.  */
663   lpbase_encoding = *p++;
664   if (lpbase_encoding != DW_EH_PE_omit)
665     p = read_encoded_value
666       (uw_context, lpbase_encoding, p, &region->lp_base);
667   else
668     region->lp_base = region->base;
669 
670   /* Find @TType, the base of the handler and exception spec type data.  */
671   region->ttype_encoding = *p++;
672   if (region->ttype_encoding != DW_EH_PE_omit)
673     {
674       p = read_uleb128 (p, &tmp);
675       region->ttype_table = p + tmp;
676     }
677    else
678      region->ttype_table = 0;
679 
680   region->ttype_base
681     = base_of_encoded_value (region->ttype_encoding, uw_context);
682 
683   /* Get the encoding and length of the call-site table; the action table
684      immediately follows.  */
685   region->call_site_encoding = *p++;
686   region->call_site_table = read_uleb128 (p, &tmp);
687 
688   region->action_table = region->call_site_table + tmp;
689 }
690 
691 
692 /* Describe an action to be taken when propagating an exception up to
693    some context.  */
694 
695 enum action_kind
696 {
697   /* Found some call site base data, but need to analyze further
698      before being able to decide.  */
699   unknown,
700 
701   /* There is nothing relevant in the context at hand. */
702   nothing,
703 
704   /* There are only cleanups to run in this context.  */
705   cleanup,
706 
707   /* There is a handler for the exception in this context.  */
708   handler,
709 
710   /* There is a handler for the exception, but it is only for catching
711      unhandled exceptions.  */
712   unhandler
713 };
714 
715 /* filter value for cleanup actions.  */
716 static const int cleanup_filter = 0;
717 
718 typedef struct
719 {
720   /* The kind of action to be taken.  */
721   enum action_kind kind;
722 
723   /* A pointer to the action record entry.  */
724   const unsigned char *table_entry;
725 
726   /* Where we should jump to actually take an action (trigger a cleanup or an
727      exception handler).  */
728   _Unwind_Ptr landing_pad;
729 
730   /* If we have a handler matching our exception, these are the filter to
731      trigger it and the corresponding id.  */
732   _Unwind_Sword ttype_filter;
733 
734 } action_descriptor;
735 
736 static void
db_action_for(action_descriptor * action,_Unwind_Ptr ip)737 db_action_for (action_descriptor *action, _Unwind_Ptr ip)
738 {
739 #ifndef inhibit_libc
740   db (DB_ACTIONS, "For ip @ %p => ", (void *)ip);
741 
742   switch (action->kind)
743      {
744      case unknown:
745        db (DB_ACTIONS, "lpad @ %p, record @ %p\n",
746 	   (void *) action->landing_pad, action->table_entry);
747        break;
748 
749      case nothing:
750        db (DB_ACTIONS, "Nothing\n");
751        break;
752 
753      case cleanup:
754        db (DB_ACTIONS, "Cleanup\n");
755        break;
756 
757      case handler:
758        db (DB_ACTIONS, "Handler, filter = %d\n", (int) action->ttype_filter);
759        break;
760 
761      default:
762        db (DB_ACTIONS, "Err? Unexpected action kind !\n");
763        break;
764     }
765 #endif
766 }
767 
768 /* Search the call_site_table of REGION for an entry appropriate for the
769    UW_CONTEXT's IP.  If one is found, store the associated landing_pad
770    and action_table entry, and set the ACTION kind to unknown for further
771    analysis.  Otherwise, set the ACTION kind to nothing.
772 
773    There are two variants of this routine, depending on the underlying
774    mechanism (DWARF/SJLJ), which account for differences in the tables.  */
775 
776 #ifdef __USING_SJLJ_EXCEPTIONS__
777 
778 #define __builtin_eh_return_data_regno(x) x
779 
780 static void
get_call_site_action_for(_Unwind_Ptr call_site,region_descriptor * region,action_descriptor * action)781 get_call_site_action_for (_Unwind_Ptr call_site,
782                           region_descriptor *region,
783                           action_descriptor *action)
784 {
785   /* call_site is a direct index into the call-site table, with two special
786      values : -1 for no-action and 0 for "terminate".  The latter should never
787      show up for Ada.  To test for the former, beware that _Unwind_Ptr might
788      be unsigned.  */
789 
790   if ((int)call_site < 0)
791     {
792       action->kind = nothing;
793     }
794   else if (call_site == 0)
795     {
796       db (DB_ERR, "========> Err, null call_site for Ada/sjlj\n");
797       action->kind = nothing;
798     }
799   else
800     {
801       _uleb128_t cs_lp, cs_action;
802       const unsigned char *p;
803 
804       /* Let the caller know there may be an action to take, but let it
805 	 determine the kind.  */
806       action->kind = unknown;
807 
808       /* We have a direct index into the call-site table, but this table is
809 	 made of leb128 values, the encoding length of which is variable.  We
810 	 can't merely compute an offset from the index, then, but have to read
811 	 all the entries before the one of interest.  */
812       p = region->call_site_table;
813       do
814 	{
815 	  p = read_uleb128 (p, &cs_lp);
816 	  p = read_uleb128 (p, &cs_action);
817 	}
818       while (--call_site);
819 
820       action->landing_pad = cs_lp + 1;
821 
822       if (cs_action)
823 	action->table_entry = region->action_table + cs_action - 1;
824       else
825 	action->table_entry = 0;
826     }
827 }
828 
829 #else /* !__USING_SJLJ_EXCEPTIONS__  */
830 
831 static void
get_call_site_action_for(_Unwind_Ptr ip,region_descriptor * region,action_descriptor * action)832 get_call_site_action_for (_Unwind_Ptr ip,
833                           region_descriptor *region,
834                           action_descriptor *action)
835 {
836   const unsigned char *p = region->call_site_table;
837 
838   /* Unless we are able to determine otherwise...  */
839   action->kind = nothing;
840 
841   db (DB_CSITE, "\n");
842 
843   while (p < region->action_table)
844     {
845       _Unwind_Ptr cs_start, cs_len, cs_lp;
846       _uleb128_t cs_action;
847 
848       /* Note that all call-site encodings are "absolute" displacements.  */
849       p = read_encoded_value (0, region->call_site_encoding, p, &cs_start);
850       p = read_encoded_value (0, region->call_site_encoding, p, &cs_len);
851       p = read_encoded_value (0, region->call_site_encoding, p, &cs_lp);
852       p = read_uleb128 (p, &cs_action);
853 
854       db (DB_CSITE,
855 	  "c_site @ %p (+%p), len = %p, lpad @ %p (+%p)\n",
856 	  (char *)region->base + cs_start, (void *)cs_start, (void *)cs_len,
857 	  (char *)region->lp_base + cs_lp, (void *)cs_lp);
858 
859       /* The table is sorted, so if we've passed the IP, stop.  */
860       if (ip < region->base + cs_start)
861  	break;
862 
863       /* If we have a match, fill the ACTION fields accordingly.  */
864       else if (ip < region->base + cs_start + cs_len)
865 	{
866 	  /* Let the caller know there may be an action to take, but let it
867 	     determine the kind.  */
868 	  action->kind = unknown;
869 
870 	  if (cs_lp)
871 	    action->landing_pad = region->lp_base + cs_lp;
872 	  else
873 	    action->landing_pad = 0;
874 
875 	  if (cs_action)
876 	    action->table_entry = region->action_table + cs_action - 1;
877 	  else
878 	    action->table_entry = 0;
879 
880 	  db (DB_CSITE, "+++\n");
881 	  return;
882 	}
883     }
884 
885   db (DB_CSITE, "---\n");
886 }
887 
888 #endif /* __USING_SJLJ_EXCEPTIONS__  */
889 
890 /* With CHOICE an exception choice representing an "exception - when"
891    argument, and PROPAGATED_EXCEPTION a pointer to the currently propagated
892    occurrence, return true if the latter matches the former, that is, if
893    PROPAGATED_EXCEPTION is caught by the handling code controlled by CHOICE.
894    This takes care of the special Non_Ada_Error case on VMS.  */
895 
896 #define Is_Handled_By_Others  __gnat_is_handled_by_others
897 #define Language_For          __gnat_language_for
898 #define Foreign_Data_For      __gnat_foreign_data_for
899 #define EID_For               __gnat_eid_for
900 
901 extern bool Is_Handled_By_Others (_Unwind_Ptr eid);
902 extern char Language_For (_Unwind_Ptr eid);
903 
904 extern void *Foreign_Data_For (_Unwind_Ptr eid);
905 
906 extern Exception_Id EID_For (_GNAT_Exception * e);
907 
908 #define Foreign_Exception system__exceptions__foreign_exception
909 extern struct Exception_Data Foreign_Exception;
910 
911 #ifdef VMS
912 #define Non_Ada_Error system__aux_dec__non_ada_error
913 extern struct Exception_Data Non_Ada_Error;
914 #endif
915 
916 /* Return true iff the exception class of EXCEPT is EC.  */
917 
918 static int
exception_class_eq(const _GNAT_Exception * except,const _Unwind_Exception_Class ec)919 exception_class_eq (const _GNAT_Exception *except,
920 		    const _Unwind_Exception_Class ec)
921 {
922 #ifdef __ARM_EABI_UNWINDER__
923   return memcmp (except->common.exception_class, ec, 8) == 0;
924 #else
925   return except->common.exception_class == ec;
926 #endif
927 }
928 
929 /* Return how CHOICE matches PROPAGATED_EXCEPTION.  */
930 
931 static enum action_kind
is_handled_by(_Unwind_Ptr choice,_GNAT_Exception * propagated_exception)932 is_handled_by (_Unwind_Ptr choice, _GNAT_Exception *propagated_exception)
933 {
934   /* All others choice match everything.  */
935   if (choice == GNAT_ALL_OTHERS)
936     return handler;
937 
938   /* GNAT exception occurrence.  */
939   if (exception_class_eq (propagated_exception, GNAT_EXCEPTION_CLASS))
940     {
941       /* Pointer to the GNAT exception data corresponding to the propagated
942          occurrence.  */
943       _Unwind_Ptr E = (_Unwind_Ptr) EID_For (propagated_exception);
944 
945       if (choice == GNAT_UNHANDLED_OTHERS)
946 	return unhandler;
947 
948       E = (_Unwind_Ptr) EID_For (propagated_exception);
949 
950       /* Base matching rules: An exception data (id) matches itself, "when
951          all_others" matches anything and "when others" matches anything
952          unless explicitly stated otherwise in the propagated occurrence.  */
953       if (choice == E || (choice == GNAT_OTHERS && Is_Handled_By_Others (E)))
954 	return handler;
955 
956 #ifdef VMS
957       /* In addition, on OpenVMS, Non_Ada_Error matches VMS exceptions, and we
958          may have different exception data pointers that should match for the
959          same condition code, if both an export and an import have been
960          registered.  The import code for both the choice and the propagated
961          occurrence are expected to have been masked off regarding severity
962          bits already (at registration time for the former and from within the
963          low level exception vector for the latter).  */
964       if ((Language_For (E) == 'V'
965 	   && choice != GNAT_OTHERS
966 	   && ((Language_For (choice) == 'V'
967 		&& Foreign_Data_For (choice) != 0
968 		&& Foreign_Data_For (choice) == Foreign_Data_For (E))
969 	       || choice == (_Unwind_Ptr)&Non_Ada_Error)))
970 	return handler;
971 #endif
972 
973       /* Otherwise, it doesn't match an Ada choice.  */
974       return nothing;
975     }
976 
977   /* All others and others choice match any foreign exception.  */
978   if (choice == GNAT_ALL_OTHERS
979       || choice == GNAT_OTHERS
980 #ifndef CERT
981       || choice == (_Unwind_Ptr) &Foreign_Exception
982 #endif
983       )
984     return handler;
985 
986 #ifndef CERT
987   /* C++ exception occurrences.  */
988   if (exception_class_eq (propagated_exception, CXX_EXCEPTION_CLASS)
989       && Language_For (choice) == 'C')
990     {
991       void *choice_typeinfo = Foreign_Data_For (choice);
992       void *except_typeinfo =
993 	(((struct __cxa_exception *)
994 	  ((_Unwind_Exception *)propagated_exception + 1)) - 1)
995 	->exceptionType;
996 
997       /* Typeinfo are directly compared, which might not be correct if they
998 	 aren't merged.  ??? We should call the == operator if this module is
999 	 compiled in C++.  */
1000       if (choice_typeinfo == except_typeinfo)
1001 	return handler;
1002     }
1003 #endif
1004 
1005   return nothing;
1006 }
1007 
1008 /* Fill out the ACTION to be taken from propagating UW_EXCEPTION up to
1009    UW_CONTEXT in REGION.  */
1010 
1011 static void
get_action_description_for(_Unwind_Ptr ip,_Unwind_Exception * uw_exception,_Unwind_Action uw_phase,region_descriptor * region,action_descriptor * action)1012 get_action_description_for (_Unwind_Ptr ip,
1013                             _Unwind_Exception *uw_exception,
1014                             _Unwind_Action uw_phase,
1015                             region_descriptor *region,
1016                             action_descriptor *action)
1017 {
1018   _GNAT_Exception *gnat_exception = (_GNAT_Exception *) uw_exception;
1019 
1020   /* Search the call site table first, which may get us a landing pad as well
1021      as the head of an action record list.  */
1022   get_call_site_action_for (ip, region, action);
1023   db_action_for (action, ip);
1024 
1025   /* If there is not even a call_site entry, we are done.  */
1026   if (action->kind == nothing)
1027     return;
1028 
1029   /* Otherwise, check what we have at the place of the call site.  */
1030 
1031   /* No landing pad => no cleanups or handlers.  */
1032   if (action->landing_pad == 0)
1033     {
1034       action->kind = nothing;
1035       return;
1036     }
1037 
1038   /* Landing pad + null table entry => only cleanups.  */
1039   else if (action->table_entry == 0)
1040     {
1041       action->kind = cleanup;
1042       action->ttype_filter = cleanup_filter;
1043       /* The filter initialization is not strictly necessary, as cleanup-only
1044 	 landing pads don't look at the filter value.  It is there to ensure
1045 	 we don't pass random values and so trigger potential confusion when
1046 	 installing the context later on.  */
1047       return;
1048     }
1049 
1050   /* Landing pad + Table entry => handlers + possible cleanups.  */
1051   else
1052     {
1053       const unsigned char * p = action->table_entry;
1054       _sleb128_t ar_filter, ar_disp;
1055 
1056       action->kind = nothing;
1057 
1058       while (1)
1059 	{
1060 	  p = read_sleb128 (p, &ar_filter);
1061 	  read_sleb128 (p, &ar_disp);
1062 	  /* Don't assign p here, as it will be incremented by ar_disp
1063 	     below.  */
1064 
1065 	  /* Null filters are for cleanups. */
1066 	  if (ar_filter == cleanup_filter)
1067 	    {
1068 	      action->kind = cleanup;
1069 	      action->ttype_filter = cleanup_filter;
1070 	      /* The filter initialization is required here, to ensure
1071 		 the target landing pad branches to the cleanup code if
1072 		 we happen not to find a matching handler.  */
1073 	    }
1074 
1075 	  /* Positive filters are for regular handlers.  */
1076 	  else if (ar_filter > 0)
1077 	    {
1078               /* Do not catch an exception if the _UA_FORCE_UNWIND flag is
1079                  passed (to follow the ABI).  */
1080               if (!(uw_phase & _UA_FORCE_UNWIND))
1081                 {
1082 		  enum action_kind act;
1083 
1084                   /* See if the filter we have is for an exception which
1085                      matches the one we are propagating.  */
1086                   _Unwind_Ptr choice =
1087 		    get_ttype_entry_for (region, ar_filter);
1088 
1089 		  act = is_handled_by (choice, gnat_exception);
1090                   if (act != nothing)
1091                     {
1092 		      action->kind = act;
1093                       action->ttype_filter = ar_filter;
1094                       return;
1095                     }
1096                 }
1097 	    }
1098 
1099 	  /* Negative filter values are for C++ exception specifications.
1100 	     Should not be there for Ada :/  */
1101 	  else
1102 	    db (DB_ERR, "========> Err, filter < 0 for Ada/dwarf\n");
1103 
1104 	  if (ar_disp == 0)
1105 	    return;
1106 
1107 	  p += ar_disp;
1108 	}
1109     }
1110 }
1111 
1112 /* Setup in UW_CONTEXT the eh return target IP and data registers, which will
1113    be restored with the others and retrieved by the landing pad once the jump
1114    occurred.  */
1115 
1116 static void
setup_to_install(_Unwind_Context * uw_context,_Unwind_Exception * uw_exception,_Unwind_Ptr uw_landing_pad,int uw_filter)1117 setup_to_install (_Unwind_Context *uw_context,
1118                   _Unwind_Exception *uw_exception,
1119                   _Unwind_Ptr uw_landing_pad,
1120                   int uw_filter)
1121 {
1122   /* 1/ exception object pointer, which might be provided back to
1123      _Unwind_Resume (and thus to this personality routine) if we are jumping
1124      to a cleanup.  */
1125   _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (0),
1126 		 (_Unwind_Word)uw_exception);
1127 
1128   /* 2/ handler switch value register, which will also be used by the target
1129      landing pad to decide what action it shall take.  */
1130   _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (1),
1131 		 (_Unwind_Word)uw_filter);
1132 
1133   /* Setup the address we should jump at to reach the code where there is the
1134      "something" we found.  */
1135   _Unwind_SetIP (uw_context, uw_landing_pad);
1136 }
1137 
1138 /* The following is defined from a-except.adb. Its purpose is to enable
1139    automatic backtraces upon exception raise, as provided through the
1140    GNAT.Traceback facilities.  */
1141 extern void __gnat_notify_handled_exception (struct Exception_Occurrence *);
1142 extern void __gnat_notify_unhandled_exception (struct Exception_Occurrence *);
1143 
1144 /* Below is the eh personality routine per se. We currently assume that only
1145    GNU-Ada exceptions are met.  */
1146 
1147 /* By default, the personality routine is public.  */
1148 #define PERSONALITY_STORAGE
1149 
1150 #ifdef __USING_SJLJ_EXCEPTIONS__
1151 #define PERSONALITY_FUNCTION    __gnat_personality_sj0
1152 #elif defined (__SEH__)
1153 #define PERSONALITY_FUNCTION    __gnat_personality_imp
1154 /* The public personality routine for seh is __gnat_personality_seh0, defined
1155    below using the SEH convention. This is a wrapper around the GNU routine,
1156    which is static.  */
1157 #undef PERSONALITY_STORAGE
1158 #define PERSONALITY_STORAGE static
1159 #else
1160 #define PERSONALITY_FUNCTION    __gnat_personality_v0
1161 #endif
1162 
1163 #if defined (__ARM_EABI_UNWINDER__) \
1164     && (defined (IN_RTS) || GCC_VERSION > 9000)
1165 #define TARGET_ATTRIBUTE __attribute__((target ("general-regs-only")))
1166 #else
1167 #define TARGET_ATTRIBUTE
1168 #endif
1169 
1170 /* Code executed to continue unwinding.  With the ARM unwinder, the
1171    personality routine must unwind one frame (per EHABI 7.3 4.).  */
1172 
1173 static _Unwind_Reason_Code
1174 TARGET_ATTRIBUTE
continue_unwind(struct _Unwind_Exception * ue_header ATTRIBUTE_UNUSED,struct _Unwind_Context * uw_context ATTRIBUTE_UNUSED)1175 continue_unwind (struct _Unwind_Exception* ue_header ATTRIBUTE_UNUSED,
1176 		 struct _Unwind_Context* uw_context ATTRIBUTE_UNUSED)
1177 {
1178 #ifdef __ARM_EABI_UNWINDER__
1179   if (__gnu_unwind_frame (ue_header, uw_context) != _URC_OK)
1180     return _URC_FAILURE;
1181 #endif
1182   return _URC_CONTINUE_UNWIND;
1183 }
1184 
1185 /* Common code for the body of GNAT personality routine.  This code is shared
1186    between all unwinders.  */
1187 
1188 static _Unwind_Reason_Code
1189 TARGET_ATTRIBUTE
personality_body(_Unwind_Action uw_phases,_Unwind_Exception * uw_exception,_Unwind_Context * uw_context)1190 personality_body (_Unwind_Action uw_phases,
1191 		  _Unwind_Exception *uw_exception,
1192 		  _Unwind_Context *uw_context)
1193 {
1194   region_descriptor region;
1195   action_descriptor action;
1196   _Unwind_Ptr ip;
1197 
1198   /* Debug traces.  */
1199   db_indent (DB_INDENT_RESET);
1200   db_phases (uw_phases);
1201   db_indent (DB_INDENT_INCREASE);
1202 
1203   /* Get the region description for the context we were provided with. This
1204      will tell us if there is some lsda, call_site, action and/or ttype data
1205      for the associated ip.  */
1206   get_region_description_for (uw_context, &region);
1207 
1208   /* No LSDA => no handlers or cleanups => we shall unwind further up.  */
1209   if (! region.lsda)
1210     return continue_unwind (uw_exception, uw_context);
1211 
1212   /* Get the instruction pointer.  */
1213   ip = get_ip_from_context (uw_context);
1214   db_region_for (&region, ip);
1215 
1216   /* Search the call-site and action-record tables for the action associated
1217      with this IP.  */
1218   get_action_description_for (ip, uw_exception, uw_phases, &region, &action);
1219   db_action_for (&action, ip);
1220 
1221   /* Whatever the phase, if there is nothing relevant in this frame,
1222      unwinding should just go on.  */
1223   if (action.kind == nothing)
1224     return continue_unwind (uw_exception, uw_context);
1225 
1226   /* If we found something in search phase, we should return a code indicating
1227      what to do next depending on what we found. If we only have cleanups
1228      around, we shall try to unwind further up to find a handler, otherwise,
1229      tell we have a handler, which will trigger the second phase.  */
1230   if (uw_phases & _UA_SEARCH_PHASE)
1231     {
1232       if (action.kind == cleanup)
1233 	{
1234 	  return continue_unwind (uw_exception, uw_context);
1235 	}
1236       else
1237 	{
1238 #ifndef CERT
1239 	  /* Trigger the appropriate notification routines before the second
1240 	     phase starts, when the stack is still intact.  First install what
1241 	     needs to be installed in the current exception buffer and fetch
1242 	     the Ada occurrence pointer to use.  */
1243 
1244 	  struct Exception_Occurrence *excep
1245 	    = __gnat_setup_current_excep (uw_exception, uw_phases);
1246 
1247 	  if (action.kind == unhandler)
1248 	    __gnat_notify_unhandled_exception (excep);
1249 	  else
1250 	    __gnat_notify_handled_exception (excep);
1251 #endif
1252 
1253 	  return _URC_HANDLER_FOUND;
1254 	}
1255     }
1256 
1257   /* We found something in cleanup/handler phase, which might be the handler
1258      or a cleanup for a handled occurrence, or a cleanup for an unhandled
1259      occurrence (we are in a FORCED_UNWIND phase in this case). Install the
1260      context to get there.  */
1261 
1262   setup_to_install
1263     (uw_context, uw_exception, action.landing_pad, action.ttype_filter);
1264 
1265 #ifndef CERT
1266   /* Write current exception so that it can be retrieved from Ada.  It was
1267      already done during phase 1, but one or several exceptions may have been
1268      raised in cleanup handlers in between.  */
1269   __gnat_setup_current_excep (uw_exception, uw_phases);
1270 #endif
1271 
1272   return _URC_INSTALL_CONTEXT;
1273 }
1274 
1275 #ifndef __ARM_EABI_UNWINDER__
1276 /* Major tweak for ia64-vms : the CHF propagation phase calls this personality
1277    routine with sigargs/mechargs arguments and has very specific expectations
1278    on possible return values.
1279 
1280    We handle this with a number of specific tricks:
1281 
1282    1. We tweak the personality routine prototype to have the "version" and
1283       "phases" two first arguments be void * instead of int and _Unwind_Action
1284       as nominally expected in the GCC context.
1285 
1286       This allows us to access the full range of bits passed in every case and
1287       has no impact on the callers side since each argument remains assigned
1288       the same single 64bit slot.
1289 
1290    2. We retrieve the corresponding int and _Unwind_Action values within the
1291       routine for regular use with truncating conversions. This is a noop when
1292       called from the libgcc unwinder.
1293 
1294    3. We assume we're called by the VMS CHF when unexpected bits are set in
1295       both those values. The incoming arguments are then real sigargs and
1296       mechargs pointers, which we then redirect to __gnat_handle_vms_condition
1297       for proper processing.
1298 */
1299 #if defined (VMS) && defined (__IA64)
1300 typedef void * version_arg_t;
1301 typedef void * phases_arg_t;
1302 #else
1303 typedef int version_arg_t;
1304 typedef _Unwind_Action phases_arg_t;
1305 #endif
1306 
1307 PERSONALITY_STORAGE _Unwind_Reason_Code
1308 PERSONALITY_FUNCTION (version_arg_t, phases_arg_t,
1309                       _Unwind_Exception_Class, _Unwind_Exception *,
1310                       _Unwind_Context *);
1311 
1312 PERSONALITY_STORAGE _Unwind_Reason_Code
PERSONALITY_FUNCTION(version_arg_t version_arg,phases_arg_t phases_arg,_Unwind_Exception_Class uw_exception_class ATTRIBUTE_UNUSED,_Unwind_Exception * uw_exception,_Unwind_Context * uw_context)1313 PERSONALITY_FUNCTION (version_arg_t version_arg,
1314                       phases_arg_t phases_arg,
1315                       _Unwind_Exception_Class uw_exception_class
1316 		         ATTRIBUTE_UNUSED,
1317                       _Unwind_Exception *uw_exception,
1318                       _Unwind_Context *uw_context)
1319 {
1320   /* Fetch the version and phases args with their nominal ABI types for later
1321      use. This is a noop everywhere except on ia64-vms when called from the
1322      Condition Handling Facility.  */
1323   int uw_version = (int) version_arg;
1324   _Unwind_Action uw_phases = (_Unwind_Action) phases_arg;
1325 
1326   /* Check that we're called from the ABI context we expect, with a major
1327      possible variation on VMS for IA64.  */
1328   if (uw_version != 1)
1329     {
1330 #if defined (VMS) && defined (__IA64)
1331 
1332       /* Assume we're called with sigargs/mechargs arguments if really
1333 	 unexpected bits are set in our first two formals.  Redirect to the
1334 	 GNAT condition handling code in this case.  */
1335 
1336       extern long __gnat_handle_vms_condition (void *, void *);
1337 
1338       unsigned int version_unexpected_bits_mask = 0xffffff00U;
1339       unsigned int phases_unexpected_bits_mask  = 0xffffff00U;
1340 
1341       if ((unsigned int)uw_version & version_unexpected_bits_mask
1342 	  && (unsigned int)uw_phases & phases_unexpected_bits_mask)
1343 	return __gnat_handle_vms_condition (version_arg, phases_arg);
1344 #endif
1345 
1346       return _URC_FATAL_PHASE1_ERROR;
1347     }
1348 
1349   return personality_body (uw_phases, uw_exception, uw_context);
1350 }
1351 
1352 #else /* __ARM_EABI_UNWINDER__ */
1353 
1354 PERSONALITY_STORAGE _Unwind_Reason_Code
1355 PERSONALITY_FUNCTION (_Unwind_State state,
1356 		      struct _Unwind_Exception* ue_header,
1357 		      struct _Unwind_Context* uw_context);
1358 
1359 PERSONALITY_STORAGE _Unwind_Reason_Code
1360 TARGET_ATTRIBUTE
PERSONALITY_FUNCTION(_Unwind_State state,struct _Unwind_Exception * uw_exception,struct _Unwind_Context * uw_context)1361 PERSONALITY_FUNCTION (_Unwind_State state,
1362 		      struct _Unwind_Exception* uw_exception,
1363 		      struct _Unwind_Context* uw_context)
1364 {
1365   _Unwind_Action uw_phases;
1366 
1367   switch (state & _US_ACTION_MASK)
1368     {
1369     case _US_VIRTUAL_UNWIND_FRAME:
1370       /* Phase 1.  */
1371       uw_phases = _UA_SEARCH_PHASE;
1372       break;
1373 
1374     case _US_UNWIND_FRAME_STARTING:
1375       /* Phase 2, to call a cleanup.  */
1376       uw_phases = _UA_CLEANUP_PHASE;
1377 #if 0
1378       /* ??? We don't use UA_HANDLER_FRAME (except to debug).  Futhermore,
1379 	 barrier_cache.sp isn't yet set.  */
1380       if (!(state & _US_FORCE_UNWIND)
1381 	  && (uw_exception->barrier_cache.sp
1382 	      == _Unwind_GetGR (uw_context, UNWIND_STACK_REG)))
1383 	uw_phases |= _UA_HANDLER_FRAME;
1384 #endif
1385       break;
1386 
1387     case _US_UNWIND_FRAME_RESUME:
1388       /* Phase 2, called at the return of a cleanup.  In the GNU
1389 	 implementation, there is nothing left to do, so we simply go on.  */
1390       return continue_unwind (uw_exception, uw_context);
1391 
1392     default:
1393       return _URC_FAILURE;
1394     }
1395   uw_phases |= (state & _US_FORCE_UNWIND);
1396 
1397   /* The dwarf unwinder assumes the context structure holds things like the
1398      function and LSDA pointers.  The ARM implementation caches these in
1399      the exception header (UCB).  To avoid rewriting everything we make a
1400      virtual scratch register point at the UCB.  This is a GNU specific
1401      requirement.  */
1402   _Unwind_SetGR (uw_context, UNWIND_POINTER_REG, (_Unwind_Ptr) uw_exception);
1403 
1404   return personality_body (uw_phases, uw_exception, uw_context);
1405 }
1406 #endif /* __ARM_EABI_UNWINDER__ */
1407 
1408 /* Callback routine called by Unwind_ForcedUnwind to execute all the cleanup
1409    before exiting the task.  */
1410 
1411 #ifndef CERT
1412 _Unwind_Reason_Code
__gnat_cleanupunwind_handler(int version ATTRIBUTE_UNUSED,_Unwind_Action phases,_Unwind_Exception_Class eclass ATTRIBUTE_UNUSED,struct _Unwind_Exception * exception,struct _Unwind_Context * context ATTRIBUTE_UNUSED,void * arg ATTRIBUTE_UNUSED)1413 __gnat_cleanupunwind_handler (int version ATTRIBUTE_UNUSED,
1414 			      _Unwind_Action phases,
1415 			      _Unwind_Exception_Class eclass ATTRIBUTE_UNUSED,
1416 			      struct _Unwind_Exception *exception,
1417 			      struct _Unwind_Context *context ATTRIBUTE_UNUSED,
1418 			      void *arg ATTRIBUTE_UNUSED)
1419 {
1420   /* Terminate when the end of the stack is reached.  */
1421   if ((phases & _UA_END_OF_STACK) != 0
1422 #if defined (__ia64__) && defined (__hpux__) && defined (USE_LIBUNWIND_EXCEPTIONS)
1423       /* Strictely follow the ia64 ABI: when end of stack is reached,
1424 	 the callback will be called with a NULL stack pointer.
1425 	 No need for that when using libgcc unwinder.  */
1426       || _Unwind_GetGR (context, 12) == 0
1427 #endif
1428       )
1429     __gnat_unhandled_except_handler (exception);
1430 
1431   /* We know there is at least one cleanup further up. Return so that it
1432      is searched and entered, after which Unwind_Resume will be called
1433      and this hook will gain control again.  */
1434   return _URC_NO_REASON;
1435 }
1436 #endif
1437 
1438 /* Define the consistently named wrappers imported by Propagate_Exception.  */
1439 
1440 _Unwind_Reason_Code
__gnat_Unwind_RaiseException(_Unwind_Exception * e)1441 __gnat_Unwind_RaiseException (_Unwind_Exception *e)
1442 {
1443 #ifdef __USING_SJLJ_EXCEPTIONS__
1444   return _Unwind_SjLj_RaiseException (e);
1445 #else
1446   return _Unwind_RaiseException (e);
1447 #endif
1448 }
1449 
1450 _Unwind_Reason_Code
__gnat_Unwind_ForcedUnwind(_Unwind_Exception * e ATTRIBUTE_UNUSED,_Unwind_Stop_Fn handler ATTRIBUTE_UNUSED,void * argument ATTRIBUTE_UNUSED)1451 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e ATTRIBUTE_UNUSED,
1452 			    _Unwind_Stop_Fn handler ATTRIBUTE_UNUSED,
1453 			    void *argument ATTRIBUTE_UNUSED)
1454 {
1455 #ifdef __USING_SJLJ_EXCEPTIONS__
1456 
1457 # if defined (__APPLE__) && defined (__arm__)
1458   /* There is not ForcedUnwind routine in arm-darwin system library.  */
1459   return _URC_FATAL_PHASE1_ERROR;
1460 # else
1461   return _Unwind_SjLj_ForcedUnwind (e, handler, argument);
1462 # endif
1463 
1464 #else
1465   return _Unwind_ForcedUnwind (e, handler, argument);
1466 #endif
1467 }
1468 
1469 #if defined (__SEH__) && !defined (__USING_SJLJ_EXCEPTIONS__)
1470 
1471 #define STATUS_USER_DEFINED		(1U << 29)
1472 
1473 /* From unwind-seh.c.  */
1474 #define GCC_MAGIC			(('G' << 16) | ('C' << 8) | 'C')
1475 #define GCC_EXCEPTION(TYPE)		\
1476        (STATUS_USER_DEFINED | ((TYPE) << 24) | GCC_MAGIC)
1477 #define STATUS_GCC_THROW		GCC_EXCEPTION (0)
1478 
1479 struct Exception_Data *
1480 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg);
1481 
1482 struct _Unwind_Exception *
1483 __gnat_create_machine_occurrence_from_signal_handler (Exception_Id,
1484 						      const char *);
1485 
1486 /* Unwind opcodes.  */
1487 #define UWOP_PUSH_NONVOL 0
1488 #define UWOP_ALLOC_LARGE 1
1489 #define UWOP_ALLOC_SMALL 2
1490 #define UWOP_SET_FPREG	 3
1491 #define UWOP_SAVE_NONVOL 4
1492 #define UWOP_SAVE_NONVOL_FAR 5
1493 #define UWOP_SAVE_XMM128 8
1494 #define UWOP_SAVE_XMM128_FAR 9
1495 #define UWOP_PUSH_MACHFRAME 10
1496 
1497 /* Modify the IP value saved in the machine frame.  This is really a kludge,
1498    that will be removed if we could propagate the Windows exception (and not
1499    the GCC one).
1500 
1501    What is very wrong is that the Windows unwinder will try to decode the
1502    instruction at IP, which isn't valid anymore after the adjustment.  */
1503 
1504 static void
__gnat_adjust_context(unsigned char * unw,ULONG64 rsp)1505 __gnat_adjust_context (unsigned char *unw, ULONG64 rsp)
1506 {
1507   unsigned int len;
1508 
1509   /* Version 1 or 2.  */
1510   if (unw[0] != 1 && unw[0] != 2)
1511     return;
1512   /* No flags, no prologue.  */
1513   if (unw[1] != 0)
1514     return;
1515   len = unw[2];
1516   /* No frame.  */
1517   if (unw[3] != 0)
1518     return;
1519   /* ??? Skip the first 2 undocumented opcodes for version 2.  */
1520   if (unw[0] == 2)
1521     unw += 8;
1522   else
1523     unw += 4;
1524   while (len > 0)
1525     {
1526       /* Offset in prologue = 0.  */
1527       if (unw[0] != 0)
1528 	return;
1529       switch (unw[1] & 0xf)
1530 	{
1531 	case UWOP_ALLOC_LARGE:
1532 	  /* Expect < 512KB.  */
1533 	  if ((unw[1] & 0xf0) != 0)
1534 	    return;
1535 	  rsp += *(unsigned short *)(unw + 2) * 8;
1536 	  len--;
1537 	  unw += 2;
1538 	  break;
1539 	case UWOP_SAVE_NONVOL:
1540 	case UWOP_SAVE_XMM128:
1541 	  len--;
1542 	  unw += 2;
1543 	  break;
1544 	case UWOP_PUSH_MACHFRAME:
1545 	  {
1546 	    ULONG64 *rip;
1547 	    rip = (ULONG64 *)rsp;
1548 	    if ((unw[1] & 0xf0) == 0x10)
1549 	      rip++;
1550 	    /* Adjust rip.  */
1551 	    (*rip)++;
1552 	  }
1553 	  return;
1554 	default:
1555 	  /* Unexpected.  */
1556 	  return;
1557 	}
1558       unw += 2;
1559       len--;
1560     }
1561 }
1562 
1563 EXCEPTION_DISPOSITION
__gnat_personality_seh0(PEXCEPTION_RECORD ms_exc,void * this_frame,PCONTEXT ms_orig_context,PDISPATCHER_CONTEXT ms_disp)1564 __gnat_personality_seh0 (PEXCEPTION_RECORD ms_exc, void *this_frame,
1565 			 PCONTEXT ms_orig_context,
1566 			 PDISPATCHER_CONTEXT ms_disp)
1567 {
1568   /* Possibly transform run-time errors into Ada exceptions.  */
1569   if (!(ms_exc->ExceptionCode & STATUS_USER_DEFINED))
1570     {
1571       struct Exception_Data *exception;
1572       const char *msg;
1573       ULONG64 excpip = (ULONG64) ms_exc->ExceptionAddress;
1574 
1575       if (excpip != 0
1576 	  && excpip >= (ms_disp->ImageBase
1577 			+ ms_disp->FunctionEntry->BeginAddress)
1578 	  && excpip < (ms_disp->ImageBase
1579 		       + ms_disp->FunctionEntry->EndAddress))
1580 	{
1581 	  /* This is a fault in this function.  We need to adjust the return
1582 	     address before raising the GCC exception.  In order to do that,
1583 	     we need to locate the machine frame that has been pushed onto
1584 	     the stack in response to the hardware exception, so we will do
1585 	     a private unwinding from here, i.e. the frame of the personality
1586 	     routine, up to the frame immediately following the frame of this
1587 	     function.  This frame corresponds to a dummy prologue which is
1588 	     never actually executed but instead appears before the real entry
1589 	     point of an interrupt routine and exists only to provide a place
1590 	     to simulate the push of a machine frame.  */
1591 	  CONTEXT context;
1592 	  PRUNTIME_FUNCTION mf_func = NULL;
1593 	  ULONG64 mf_imagebase;
1594 	  ULONG64 mf_rsp = 0;
1595 
1596 	  /* Get the current context.  */
1597 	  RtlCaptureContext (&context);
1598 
1599 	  while (1)
1600 	    {
1601 	      PRUNTIME_FUNCTION RuntimeFunction;
1602 	      ULONG64 ImageBase;
1603 	      VOID *HandlerData;
1604 	      ULONG64 EstablisherFrame;
1605 
1606 	      /* Get function metadata.  */
1607 	      RuntimeFunction
1608 		= RtlLookupFunctionEntry (context.Rip, &ImageBase,
1609 					  ms_disp->HistoryTable);
1610 
1611 	      /* Stop once we reached the frame of this function.  */
1612 	      if (RuntimeFunction == ms_disp->FunctionEntry)
1613 		break;
1614 
1615 	      mf_func = RuntimeFunction;
1616 	      mf_imagebase = ImageBase;
1617 	      mf_rsp = context.Rsp;
1618 
1619 	      if (RuntimeFunction)
1620 		{
1621 		  /* Unwind.  */
1622 		  RtlVirtualUnwind (0, ImageBase, context.Rip, RuntimeFunction,
1623 				    &context, &HandlerData, &EstablisherFrame,
1624 				    NULL);
1625 		}
1626 	      else
1627 		{
1628 		  /* In case of failure, assume this is a leaf function.  */
1629 		  context.Rip = *(ULONG64 *) context.Rsp;
1630 		  context.Rsp += 8;
1631 		}
1632 
1633 	      /* 0 means bottom of the stack.  */
1634 	      if (context.Rip == 0)
1635 		{
1636 		  mf_func = NULL;
1637 		  break;
1638 		}
1639 	    }
1640 
1641 	  /* If we have found the machine frame, adjust the return address.  */
1642 	  if (mf_func != NULL)
1643 	    __gnat_adjust_context
1644 	      ((unsigned char *)(mf_imagebase + mf_func->UnwindData), mf_rsp);
1645 	}
1646 
1647       exception = __gnat_map_SEH (ms_exc, &msg);
1648       if (exception != NULL)
1649 	{
1650 	  /* Directly convert the system exception into a GCC one.
1651 
1652 	     This is really breaking the API, but is necessary for stack size
1653 	     reasons: the normal way is to call Raise_From_Signal_Handler,
1654 	     which builds the exception and calls _Unwind_RaiseException,
1655 	     which unwinds the stack and will call this personality routine.
1656 	     But the Windows unwinder needs about 2KB of stack.  */
1657 	  struct _Unwind_Exception *exc
1658 	    = __gnat_create_machine_occurrence_from_signal_handler (exception,
1659 								    msg);
1660 	  memset (exc->private_, 0, sizeof (exc->private_));
1661 	  ms_exc->ExceptionCode = STATUS_GCC_THROW;
1662 	  ms_exc->NumberParameters = 1;
1663 	  ms_exc->ExceptionInformation[0] = (ULONG_PTR)exc;
1664 	}
1665 
1666     }
1667 
1668   return
1669     _GCC_specific_handler (ms_exc, this_frame, ms_orig_context, ms_disp,
1670 			   __gnat_personality_imp);
1671 }
1672 
1673 #endif /* SEH */
1674 
1675 #if !defined (__USING_SJLJ_EXCEPTIONS__)
1676 /* Size of the _Unwind_Exception structure.  This is used by g-cppexc to get
1677    the offset to the C++ object.  */
1678 
1679 const int __gnat_unwind_exception_size = sizeof (_Unwind_Exception);
1680 #endif
1681 
1682 #ifdef __cplusplus
1683 }
1684 #endif
1685