OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / ada / raise-gcc.c
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-2008, 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 2,  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.  See the GNU General Public License *
17  * for  more details.  You should have  received  a copy of the GNU General *
18  * Public License  distributed with GNAT;  see file COPYING.  If not, write *
19  * to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, *
20  * Boston, MA 02110-1301, USA.                                              *
21  *                                                                          *
22  * As a  special  exception,  if you  link  this file  with other  files to *
23  * produce an executable,  this file does not by itself cause the resulting *
24  * executable to be covered by the GNU General Public License. This except- *
25  * ion does not  however invalidate  any other reasons  why the  executable *
26  * file might be covered by the  GNU Public License.                        *
27  *                                                                          *
28  * GNAT was originally developed  by the GNAT team at  New York University. *
29  * Extensive contributions were provided by Ada Core Technologies Inc.      *
30  *                                                                          *
31  ****************************************************************************/
32
33 /* Code related to the integration of the GCC mechanism for exception
34    handling.  */
35
36 #ifdef IN_RTS
37 #include "tconfig.h"
38 #include "tsystem.h"
39 /* In the top-of-tree GCC, tconfig does not include tm.h, but in GCC 3.2
40    it does.  To avoid branching raise.c just for that purpose, we kludge by
41    looking for a symbol always defined by tm.h and if it's not defined,
42    we include it.  */
43 #ifndef FIRST_PSEUDO_REGISTER
44 #include "coretypes.h"
45 #include "tm.h"
46 #endif
47 #include <sys/stat.h>
48 #include <stdarg.h>
49 typedef char bool;
50 # define true 1
51 # define false 0
52 #else
53 #include "config.h"
54 #include "system.h"
55 #endif
56
57 #include "adaint.h"
58 #include "raise.h"
59
60 /* The names of a couple of "standard" routines for unwinding/propagation
61    actually vary depending on the underlying GCC scheme for exception handling
62    (SJLJ or DWARF). We need a consistently named interface to import from
63    a-except, so wrappers are defined here.
64
65    Besides, even though the compiler is never setup to use the GCC propagation
66    circuitry, it still relies on exceptions internally and part of the sources
67    to handle to exceptions are shared with the run-time library.  We need
68    dummy definitions for the wrappers to satisfy the linker in this case.
69
70    The types to be used by those wrappers in the run-time library are target
71    types exported by unwind.h.  We used to piggyback on them for the compiler
72    stubs, but there is no guarantee that unwind.h is always in sight so we
73    define our own set below.  These are dummy types as the wrappers are never
74    called in the compiler case.  */
75
76 #ifdef IN_RTS
77
78 #include "unwind.h"
79
80 typedef struct _Unwind_Context _Unwind_Context;
81 typedef struct _Unwind_Exception _Unwind_Exception;
82
83 #else
84
85 typedef void _Unwind_Context;
86 typedef void _Unwind_Exception;
87 typedef int  _Unwind_Reason_Code;
88
89 #endif
90
91 _Unwind_Reason_Code
92 __gnat_Unwind_RaiseException (_Unwind_Exception *);
93
94 _Unwind_Reason_Code
95 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *, void *, void *);
96
97
98 #ifdef IN_RTS   /* For eh personality routine */
99
100 #include "dwarf2.h"
101 #include "unwind-dw2-fde.h"
102 #include "unwind-pe.h"
103
104
105 /* --------------------------------------------------------------
106    -- The DB stuff below is there for debugging purposes only. --
107    -------------------------------------------------------------- */
108
109 #define DB_PHASES     0x1
110 #define DB_CSITE      0x2
111 #define DB_ACTIONS    0x4
112 #define DB_REGIONS    0x8
113
114 #define DB_ERR        0x1000
115
116 /* The "action" stuff below is also there for debugging purposes only.  */
117
118 typedef struct
119 {
120   _Unwind_Action phase;
121   char * description;
122 } phase_descriptor;
123
124 static phase_descriptor phase_descriptors[]
125   = {{ _UA_SEARCH_PHASE,  "SEARCH_PHASE" },
126      { _UA_CLEANUP_PHASE, "CLEANUP_PHASE" },
127      { _UA_HANDLER_FRAME, "HANDLER_FRAME" },
128      { _UA_FORCE_UNWIND,  "FORCE_UNWIND" },
129      { -1, 0}};
130
131 static int
132 db_accepted_codes (void)
133 {
134   static int accepted_codes = -1;
135
136   if (accepted_codes == -1)
137     {
138       char * db_env = (char *) getenv ("EH_DEBUG");
139
140       accepted_codes = db_env ? (atoi (db_env) | DB_ERR) : 0;
141       /* Arranged for ERR stuff to always be visible when the variable
142          is defined. One may just set the variable to 0 to see the ERR
143          stuff only.  */
144     }
145
146   return accepted_codes;
147 }
148
149 #define DB_INDENT_INCREASE 0x01
150 #define DB_INDENT_DECREASE 0x02
151 #define DB_INDENT_OUTPUT   0x04
152 #define DB_INDENT_NEWLINE  0x08
153 #define DB_INDENT_RESET    0x10
154
155 #define DB_INDENT_UNIT     8
156
157 static void
158 db_indent (int requests)
159 {
160   static int current_indentation_level = 0;
161
162   if (requests & DB_INDENT_RESET)
163     {
164       current_indentation_level = 0;
165     }
166
167   if (requests & DB_INDENT_INCREASE)
168     {
169       current_indentation_level ++;
170     }
171
172   if (requests & DB_INDENT_DECREASE)
173     {
174       current_indentation_level --;
175     }
176
177   if (requests & DB_INDENT_NEWLINE)
178     {
179       fprintf (stderr, "\n");
180     }
181
182   if (requests & DB_INDENT_OUTPUT)
183     {
184       fprintf (stderr, "%*s",
185                current_indentation_level * DB_INDENT_UNIT, " ");
186     }
187
188 }
189
190 static void ATTRIBUTE_PRINTF_2
191 db (int db_code, char * msg_format, ...)
192 {
193   if (db_accepted_codes () & db_code)
194     {
195       va_list msg_args;
196
197       db_indent (DB_INDENT_OUTPUT);
198
199       va_start (msg_args, msg_format);
200       vfprintf (stderr, msg_format, msg_args);
201       va_end (msg_args);
202     }
203 }
204
205 static void
206 db_phases (int phases)
207 {
208   phase_descriptor *a = phase_descriptors;
209
210   if (! (db_accepted_codes() & DB_PHASES))
211     return;
212
213   db (DB_PHASES, "\n");
214
215   for (; a->description != 0; a++)
216     if (phases & a->phase)
217       db (DB_PHASES, "%s ", a->description);
218
219   db (DB_PHASES, " :\n");
220 }
221
222
223 /* ---------------------------------------------------------------
224    --  Now come a set of useful structures and helper routines. --
225    --------------------------------------------------------------- */
226
227 /* There are three major runtime tables involved, generated by the
228    GCC back-end. Contents slightly vary depending on the underlying
229    implementation scheme (dwarf zero cost / sjlj).
230
231    =======================================
232    * Tables for the dwarf zero cost case *
233    =======================================
234
235    call_site []
236    -------------------------------------------------------------------
237    * region-start | region-length | landing-pad | first-action-index *
238    -------------------------------------------------------------------
239
240    Identify possible actions to be taken and where to resume control
241    for that when an exception propagates through a pc inside the region
242    delimited by start and length.
243
244    A null landing-pad indicates that nothing is to be done.
245
246    Otherwise, first-action-index provides an entry into the action[]
247    table which heads a list of possible actions to be taken (see below).
248
249    If it is determined that indeed an action should be taken, that
250    is, if one action filter matches the exception being propagated,
251    then control should be transfered to landing-pad.
252
253    A null first-action-index indicates that there are only cleanups
254    to run there.
255
256    action []
257    -------------------------------
258    * action-filter | next-action *
259    -------------------------------
260
261    This table contains lists (called action chains) of possible actions
262    associated with call-site entries described in the call-site [] table.
263    There is at most one action list per call-site entry.
264
265    A null action-filter indicates a cleanup.
266
267    Non null action-filters provide an index into the ttypes [] table
268    (see below), from which information may be retrieved to check if it
269    matches the exception being propagated.
270
271    action-filter > 0  means there is a regular handler to be run,
272
273    action-filter < 0  means there is a some "exception_specification"
274                       data to retrieve, which is only relevant for C++
275                       and should never show up for Ada.
276
277    next-action indexes the next entry in the list. 0 indicates there is
278    no other entry.
279
280    ttypes []
281    ---------------
282    * ttype-value *
283    ---------------
284
285    A null value indicates a catch-all handler in C++, and an "others"
286    handler in Ada.
287
288    Non null values are used to match the exception being propagated:
289    In C++ this is a pointer to some rtti data, while in Ada this is an
290    exception id.
291
292    The special id value 1 indicates an "all_others" handler.
293
294    For C++, this table is actually also used to store "exception
295    specification" data. The differentiation between the two kinds
296    of entries is made by the sign of the associated action filter,
297    which translates into positive or negative offsets from the
298    so called base of the table:
299
300    Exception Specification data is stored at positive offsets from
301    the ttypes table base, which Exception Type data is stored at
302    negative offsets:
303
304    ---------------------------------------------------------------------------
305
306    Here is a quick summary of the tables organization:
307
308           +-- Unwind_Context (pc, ...)
309           |
310           |(pc)
311           |
312           |   CALL-SITE[]
313           |
314           |   +=============================================================+
315           |   | region-start + length |  landing-pad   | first-action-index |
316           |   +=============================================================+
317           +-> |       pc range          0 => no-action   0 => cleanups only |
318               |                         !0 => jump @              N --+     |
319               +====================================================== | ====+
320                                                                       |
321                                                                       |
322        ACTION []                                                      |
323                                                                       |
324        +==========================================================+   |
325        |              action-filter           |   next-action     |   |
326        +==========================================================+   |
327        |  0 => cleanup                                            |   |
328        | >0 => ttype index for handler ------+  0 => end of chain | <-+
329        | <0 => ttype index for spec data     |                    |
330        +==================================== | ===================+
331                                              |
332                                              |
333        TTYPES []                             |
334                                              |  Offset negated from
335                  +=====================+     |  the actual base.
336                  |     ttype-value     |     |
337     +============+=====================+     |
338     |            |  0 => "others"      |     |
339     |    ...     |  1 => "all others"  | <---+
340     |            |  X => exception id  |
341     |  handlers  +---------------------+
342     |            |        ...          |
343     |    ...     |        ...          |
344     |            |        ...          |
345     +============+=====================+ <<------ Table base
346     |    ...     |        ...          |
347     |   specs    |        ...          | (should not see negative filter
348     |    ...     |        ...          |  values for Ada).
349     +============+=====================+
350
351
352    ============================
353    * Tables for the sjlj case *
354    ============================
355
356    So called "function contexts" are pushed on a context stack by calls to
357    _Unwind_SjLj_Register on function entry, and popped off at exit points by
358    calls to _Unwind_SjLj_Unregister. The current call_site for a function is
359    updated in the function context as the function's code runs along.
360
361    The generic unwinding engine in _Unwind_RaiseException walks the function
362    context stack and not the actual call chain.
363
364    The ACTION and TTYPES tables remain unchanged, which allows to search them
365    during the propagation phase to determine whether or not the propagated
366    exception is handled somewhere. When it is, we only "jump" up once directly
367    to the context where the handler will be found. Besides, this allows "break
368    exception unhandled" to work also
369
370    The CALL-SITE table is setup differently, though: the pc attached to the
371    unwind context is a direct index into the table, so the entries in this
372    table do not hold region bounds any more.
373
374    A special index (-1) is used to indicate that no action is possibly
375    connected with the context at hand, so null landing pads cannot appear
376    in the table.
377
378    Additionally, landing pad values in the table do not represent code address
379    to jump at, but so called "dispatch" indices used by a common landing pad
380    for the function to switch to the appropriate post-landing-pad.
381
382    +-- Unwind_Context (pc, ...)
383    |
384    | pc = call-site index
385    |  0 => terminate (should not see this for Ada)
386    | -1 => no-action
387    |
388    |   CALL-SITE[]
389    |
390    |   +=====================================+
391    |   |  landing-pad   | first-action-index |
392    |   +=====================================+
393    +-> |                  0 => cleanups only |
394        | dispatch index             N        |
395        +=====================================+
396
397
398    ===================================
399    * Basic organization of this unit *
400    ===================================
401
402    The major point of this unit is to provide an exception propagation
403    personality routine for Ada. This is __gnat_eh_personality.
404
405    It is provided with a pointer to the propagated exception, an unwind
406    context describing a location the propagation is going through, and a
407    couple of other arguments including a description of the current
408    propagation phase.
409
410    It shall return to the generic propagation engine what is to be performed
411    next, after possible context adjustments, depending on what it finds in the
412    traversed context (a handler for the exception, a cleanup, nothing, ...),
413    and on the propagation phase.
414
415    A number of structures and subroutines are used for this purpose, as
416    sketched below:
417
418    o region_descriptor: General data associated with the context (base pc,
419      call-site table, action table, ttypes table, ...)
420
421    o action_descriptor: Data describing the action to be taken for the
422      propagated exception in the provided context (kind of action: nothing,
423      handler, cleanup; pointer to the action table entry, ...).
424
425    raise
426      |
427     ... (a-except.adb)
428      |
429    Propagate_Exception (a-exexpr.adb)
430      |
431      |
432    _Unwind_RaiseException (libgcc)
433      |
434      |   (Ada frame)
435      |
436      +--> __gnat_eh_personality (context, exception)
437            |
438            +--> get_region_descriptor_for (context)
439            |
440            +--> get_action_descriptor_for (context, exception, region)
441            |       |
442            |       +--> get_call_site_action_for (context, region)
443            |            (one version for each underlying scheme)
444            |
445            +--> setup_to_install (context)
446
447    This unit is inspired from the C++ version found in eh_personality.cc,
448    part of libstdc++-v3.
449
450 */
451
452
453 /* This is an incomplete "proxy" of the structure of exception objects as
454    built by the GNAT runtime library. Accesses to other fields than the common
455    header are performed through subprogram calls to alleviate the need of an
456    exact counterpart here and potential alignment/size issues for the common
457    header. See a-exexpr.adb.  */
458
459 typedef struct
460 {
461   _Unwind_Exception common;
462   /* ABI header, maximally aligned. */
463 } _GNAT_Exception;
464
465 /* The two constants below are specific ttype identifiers for special
466    exception ids.  Their type should match what a-exexpr exports.  */
467
468 extern const int __gnat_others_value;
469 #define GNAT_OTHERS      ((_Unwind_Ptr) &__gnat_others_value)
470
471 extern const int __gnat_all_others_value;
472 #define GNAT_ALL_OTHERS  ((_Unwind_Ptr) &__gnat_all_others_value)
473
474 /* Describe the useful region data associated with an unwind context.  */
475
476 typedef struct
477 {
478   /* The base pc of the region.  */
479   _Unwind_Ptr base;
480
481   /* Pointer to the Language Specific Data for the region.  */
482   _Unwind_Ptr lsda;
483
484   /* Call-Site data associated with this region.  */
485   unsigned char call_site_encoding;
486   const unsigned char *call_site_table;
487
488   /* The base to which are relative landing pad offsets inside the call-site
489      entries .  */
490   _Unwind_Ptr lp_base;
491
492   /* Action-Table associated with this region.  */
493   const unsigned char *action_table;
494
495   /* Ttype data associated with this region.  */
496   unsigned char ttype_encoding;
497   const unsigned char *ttype_table;
498   _Unwind_Ptr ttype_base;
499
500 } region_descriptor;
501
502 static void
503 db_region_for (region_descriptor *region, _Unwind_Context *uw_context)
504 {
505   _Unwind_Ptr ip = _Unwind_GetIP (uw_context) - 1;
506
507   if (! (db_accepted_codes () & DB_REGIONS))
508     return;
509
510   db (DB_REGIONS, "For ip @ 0x%08x => ", ip);
511
512   if (region->lsda)
513     db (DB_REGIONS, "lsda @ 0x%x", region->lsda);
514   else
515     db (DB_REGIONS, "no lsda");
516
517   db (DB_REGIONS, "\n");
518 }
519
520 /* Retrieve the ttype entry associated with FILTER in the REGION's
521    ttype table.  */
522
523 static const _Unwind_Ptr
524 get_ttype_entry_for (region_descriptor *region, long filter)
525 {
526   _Unwind_Ptr ttype_entry;
527
528   filter *= size_of_encoded_value (region->ttype_encoding);
529   read_encoded_value_with_base
530     (region->ttype_encoding, region->ttype_base,
531      region->ttype_table - filter, &ttype_entry);
532
533   return ttype_entry;
534 }
535
536 /* Fill out the REGION descriptor for the provided UW_CONTEXT.  */
537
538 static void
539 get_region_description_for (_Unwind_Context *uw_context,
540                             region_descriptor *region)
541 {
542   const unsigned char * p;
543   _uleb128_t tmp;
544   unsigned char lpbase_encoding;
545
546   /* Get the base address of the lsda information. If the provided context
547      is null or if there is no associated language specific data, there's
548      nothing we can/should do.  */
549   region->lsda
550     = (_Unwind_Ptr) (uw_context
551                      ? _Unwind_GetLanguageSpecificData (uw_context) : 0);
552
553   if (! region->lsda)
554     return;
555
556   /* Parse the lsda and fill the region descriptor.  */
557   p = (char *)region->lsda;
558
559   region->base = _Unwind_GetRegionStart (uw_context);
560
561   /* Find @LPStart, the base to which landing pad offsets are relative.  */
562   lpbase_encoding = *p++;
563   if (lpbase_encoding != DW_EH_PE_omit)
564     p = read_encoded_value
565       (uw_context, lpbase_encoding, p, &region->lp_base);
566   else
567     region->lp_base = region->base;
568
569   /* Find @TType, the base of the handler and exception spec type data.  */
570   region->ttype_encoding = *p++;
571   if (region->ttype_encoding != DW_EH_PE_omit)
572     {
573       p = read_uleb128 (p, &tmp);
574       region->ttype_table = p + tmp;
575     }
576    else
577      region->ttype_table = 0;
578
579   region->ttype_base
580     = base_of_encoded_value (region->ttype_encoding, uw_context);
581
582   /* Get the encoding and length of the call-site table; the action table
583      immediately follows.  */
584   region->call_site_encoding = *p++;
585   region->call_site_table = read_uleb128 (p, &tmp);
586
587   region->action_table = region->call_site_table + tmp;
588 }
589
590
591 /* Describe an action to be taken when propagating an exception up to
592    some context.  */
593
594 typedef enum
595 {
596   /* Found some call site base data, but need to analyze further
597      before being able to decide.  */
598   unknown,
599
600   /* There is nothing relevant in the context at hand. */
601   nothing,
602
603   /* There are only cleanups to run in this context.  */
604   cleanup,
605
606   /* There is a handler for the exception in this context.  */
607   handler
608 } action_kind;
609
610 /* filter value for cleanup actions.  */
611 const int cleanup_filter = 0;
612
613 typedef struct
614 {
615   /* The kind of action to be taken.  */
616   action_kind kind;
617
618   /* A pointer to the action record entry.  */
619   const unsigned char *table_entry;
620
621   /* Where we should jump to actually take an action (trigger a cleanup or an
622      exception handler).  */
623   _Unwind_Ptr landing_pad;
624
625   /* If we have a handler matching our exception, these are the filter to
626      trigger it and the corresponding id.  */
627   _Unwind_Sword ttype_filter;
628   _Unwind_Ptr   ttype_entry;
629
630 } action_descriptor;
631
632 static void
633 db_action_for (action_descriptor *action, _Unwind_Context *uw_context)
634 {
635   _Unwind_Ptr ip = _Unwind_GetIP (uw_context) - 1;
636
637   db (DB_ACTIONS, "For ip @ 0x%08x => ", ip);
638
639   switch (action->kind)
640      {
641      case unknown:
642        db (DB_ACTIONS, "lpad @ 0x%x, record @ 0x%x\n",
643            action->landing_pad, action->table_entry);
644        break;
645
646      case nothing:
647        db (DB_ACTIONS, "Nothing\n");
648        break;
649
650      case cleanup:
651        db (DB_ACTIONS, "Cleanup\n");
652        break;
653
654      case handler:
655        db (DB_ACTIONS, "Handler, filter = %d\n", action->ttype_filter);
656        break;
657
658      default:
659        db (DB_ACTIONS, "Err? Unexpected action kind !\n");
660        break;
661     }
662
663   return;
664 }
665
666 /* Search the call_site_table of REGION for an entry appropriate for the
667    UW_CONTEXT's IP.  If one is found, store the associated landing_pad
668    and action_table entry, and set the ACTION kind to unknown for further
669    analysis.  Otherwise, set the ACTION kind to nothing.
670
671    There are two variants of this routine, depending on the underlying
672    mechanism (DWARF/SJLJ), which account for differences in the tables.  */
673
674 #ifdef __APPLE__
675 /* On MacOS X, versions older than 10.5 don't export _Unwind_GetIPInfo.  */
676 #undef HAVE_GETIPINFO
677 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
678 #define HAVE_GETIPINFO 1
679 #endif
680 #endif
681
682 #ifdef __USING_SJLJ_EXCEPTIONS__
683
684 #define __builtin_eh_return_data_regno(x) x
685
686 static void
687 get_call_site_action_for (_Unwind_Context *uw_context,
688                           region_descriptor *region,
689                           action_descriptor *action)
690 {
691   int ip_before_insn = 0;
692 #ifdef HAVE_GETIPINFO
693   _Unwind_Ptr call_site = _Unwind_GetIPInfo (uw_context, &ip_before_insn);
694 #else
695   _Unwind_Ptr call_site = _Unwind_GetIP (uw_context);
696 #endif
697   /* Subtract 1 if necessary because GetIPInfo returns the actual call site
698      value + 1 in this case.  */
699   if (!ip_before_insn)
700     call_site--;
701
702   /* call_site is a direct index into the call-site table, with two special
703      values : -1 for no-action and 0 for "terminate".  The latter should never
704      show up for Ada.  To test for the former, beware that _Unwind_Ptr might
705      be unsigned.  */
706
707   if ((int)call_site < 0)
708     {
709       action->kind = nothing;
710       return;
711     }
712   else if (call_site == 0)
713     {
714       db (DB_ERR, "========> Err, null call_site for Ada/sjlj\n");
715       action->kind = nothing;
716       return;
717     }
718   else
719     {
720       _uleb128_t cs_lp, cs_action;
721
722       /* Let the caller know there may be an action to take, but let it
723          determine the kind.  */
724       action->kind = unknown;
725
726       /* We have a direct index into the call-site table, but this table is
727          made of leb128 values, the encoding length of which is variable.  We
728          can't merely compute an offset from the index, then, but have to read
729          all the entries before the one of interest.  */
730
731       const unsigned char *p = region->call_site_table;
732
733       do {
734         p = read_uleb128 (p, &cs_lp);
735         p = read_uleb128 (p, &cs_action);
736       } while (--call_site);
737
738       action->landing_pad = cs_lp + 1;
739
740       if (cs_action)
741         action->table_entry = region->action_table + cs_action - 1;
742       else
743         action->table_entry = 0;
744
745       return;
746     }
747 }
748
749 #else /* !__USING_SJLJ_EXCEPTIONS__  */
750
751 static void
752 get_call_site_action_for (_Unwind_Context *uw_context,
753                           region_descriptor *region,
754                           action_descriptor *action)
755 {
756   const unsigned char *p = region->call_site_table;
757   int ip_before_insn = 0;
758 #ifdef HAVE_GETIPINFO
759   _Unwind_Ptr ip = _Unwind_GetIPInfo (uw_context, &ip_before_insn);
760 #else
761   _Unwind_Ptr ip = _Unwind_GetIP (uw_context);
762 #endif
763   /* Subtract 1 if necessary because GetIPInfo yields a call return address
764      in this case, while we are interested in information for the call point.
765      This does not always yield the exact call instruction address but always
766      brings the IP back within the corresponding region.  */
767   if (!ip_before_insn)
768     ip--;
769
770   /* Unless we are able to determine otherwise...  */
771   action->kind = nothing;
772
773   db (DB_CSITE, "\n");
774
775   while (p < region->action_table)
776     {
777       _Unwind_Ptr cs_start, cs_len, cs_lp;
778       _uleb128_t cs_action;
779
780       /* Note that all call-site encodings are "absolute" displacements.  */
781       p = read_encoded_value (0, region->call_site_encoding, p, &cs_start);
782       p = read_encoded_value (0, region->call_site_encoding, p, &cs_len);
783       p = read_encoded_value (0, region->call_site_encoding, p, &cs_lp);
784       p = read_uleb128 (p, &cs_action);
785
786       db (DB_CSITE,
787           "c_site @ 0x%08x (+0x%03x), len = %3d, lpad @ 0x%08x (+0x%03x)\n",
788           region->base+cs_start, cs_start, cs_len,
789           region->lp_base+cs_lp, cs_lp);
790
791       /* The table is sorted, so if we've passed the IP, stop.  */
792       if (ip < region->base + cs_start)
793         break;
794
795       /* If we have a match, fill the ACTION fields accordingly.  */
796       else if (ip < region->base + cs_start + cs_len)
797         {
798           /* Let the caller know there may be an action to take, but let it
799              determine the kind.  */
800           action->kind = unknown;
801
802           if (cs_lp)
803             action->landing_pad = region->lp_base + cs_lp;
804           else
805             action->landing_pad = 0;
806
807           if (cs_action)
808             action->table_entry = region->action_table + cs_action - 1;
809           else
810             action->table_entry = 0;
811
812           db (DB_CSITE, "+++\n");
813           return;
814         }
815     }
816
817   db (DB_CSITE, "---\n");
818 }
819
820 #endif /* __USING_SJLJ_EXCEPTIONS__  */
821
822 /* With CHOICE an exception choice representing an "exception - when"
823    argument, and PROPAGATED_EXCEPTION a pointer to the currently propagated
824    occurrence, return true if the latter matches the former, that is, if
825    PROPAGATED_EXCEPTION is caught by the handling code controlled by CHOICE.
826    This takes care of the special Non_Ada_Error case on VMS.  */
827
828 #define Is_Handled_By_Others  __gnat_is_handled_by_others
829 #define Language_For          __gnat_language_for
830 #define Import_Code_For       __gnat_import_code_for
831 #define EID_For               __gnat_eid_for
832 #define Adjust_N_Cleanups_For __gnat_adjust_n_cleanups_for
833
834 extern bool Is_Handled_By_Others (_Unwind_Ptr eid);
835 extern char Language_For (_Unwind_Ptr eid);
836
837 extern Exception_Code Import_Code_For (_Unwind_Ptr eid);
838
839 extern Exception_Id EID_For (_GNAT_Exception * e);
840 extern void Adjust_N_Cleanups_For (_GNAT_Exception * e, int n);
841
842 static int
843 is_handled_by (_Unwind_Ptr choice, _GNAT_Exception * propagated_exception)
844 {
845   /* Pointer to the GNAT exception data corresponding to the propagated
846      occurrence.  */
847   _Unwind_Ptr E = (_Unwind_Ptr) EID_For (propagated_exception);
848
849   /* Base matching rules: An exception data (id) matches itself, "when
850      all_others" matches anything and "when others" matches anything unless
851      explicitly stated otherwise in the propagated occurrence.  */
852
853   bool is_handled =
854     choice == E
855     || choice == GNAT_ALL_OTHERS
856     || (choice == GNAT_OTHERS && Is_Handled_By_Others (E));
857
858   /* In addition, on OpenVMS, Non_Ada_Error matches VMS exceptions, and we
859      may have different exception data pointers that should match for the
860      same condition code, if both an export and an import have been
861      registered.  The import code for both the choice and the propagated
862      occurrence are expected to have been masked off regarding severity
863      bits already (at registration time for the former and from within the
864      low level exception vector for the latter).  */
865 #ifdef VMS
866   #define Non_Ada_Error system__aux_dec__non_ada_error
867   extern struct Exception_Data Non_Ada_Error;
868
869   is_handled |=
870     (Language_For (E) == 'V'
871      && choice != GNAT_OTHERS && choice != GNAT_ALL_OTHERS
872      && ((Language_For (choice) == 'V' && Import_Code_For (choice) != 0
873           && Import_Code_For (choice) == Import_Code_For (E))
874          || choice == (_Unwind_Ptr)&Non_Ada_Error));
875 #endif
876
877   return is_handled;
878 }
879
880 /* Fill out the ACTION to be taken from propagating UW_EXCEPTION up to
881    UW_CONTEXT in REGION.  */
882
883 static void
884 get_action_description_for (_Unwind_Context *uw_context,
885                             _Unwind_Exception *uw_exception,
886                             region_descriptor *region,
887                             action_descriptor *action)
888 {
889   _GNAT_Exception * gnat_exception = (_GNAT_Exception *) uw_exception;
890
891   /* Search the call site table first, which may get us a landing pad as well
892      as the head of an action record list.  */
893   get_call_site_action_for (uw_context, region, action);
894   db_action_for (action, uw_context);
895
896   /* If there is not even a call_site entry, we are done.  */
897   if (action->kind == nothing)
898     return;
899
900   /* Otherwise, check what we have at the place of the call site.  */
901
902   /* No landing pad => no cleanups or handlers.  */
903   if (action->landing_pad == 0)
904     {
905       action->kind = nothing;
906       return;
907     }
908
909   /* Landing pad + null table entry => only cleanups.  */
910   else if (action->table_entry == 0)
911     {
912       action->kind = cleanup;
913       action->ttype_filter = cleanup_filter;
914       /* The filter initialization is not strictly necessary, as cleanup-only
915          landing pads don't look at the filter value.  It is there to ensure
916          we don't pass random values and so trigger potential confusion when
917          installing the context later on.  */
918       return;
919     }
920
921   /* Landing pad + Table entry => handlers + possible cleanups.  */
922   else
923     {
924       const unsigned char * p = action->table_entry;
925
926       _sleb128_t ar_filter, ar_disp;
927
928       action->kind = nothing;
929
930       while (1)
931         {
932           p = read_sleb128 (p, &ar_filter);
933           read_sleb128 (p, &ar_disp);
934           /* Don't assign p here, as it will be incremented by ar_disp
935              below.  */
936
937           /* Null filters are for cleanups. */
938           if (ar_filter == cleanup_filter)
939             {
940               action->kind = cleanup;
941               action->ttype_filter = cleanup_filter;
942               /* The filter initialization is required here, to ensure
943                  the target landing pad branches to the cleanup code if
944                  we happen not to find a matching handler.  */
945             }
946
947           /* Positive filters are for regular handlers.  */
948           else if (ar_filter > 0)
949             {
950               /* See if the filter we have is for an exception which matches
951                  the one we are propagating.  */
952               _Unwind_Ptr choice = get_ttype_entry_for (region, ar_filter);
953
954               if (is_handled_by (choice, gnat_exception))
955                 {
956                   action->kind = handler;
957                   action->ttype_filter = ar_filter;
958                   action->ttype_entry = choice;
959                   return;
960                 }
961             }
962
963           /* Negative filter values are for C++ exception specifications.
964              Should not be there for Ada :/  */
965           else
966             db (DB_ERR, "========> Err, filter < 0 for Ada/dwarf\n");
967
968           if (ar_disp == 0)
969             return;
970
971           p += ar_disp;
972         }
973     }
974 }
975
976 /* Setup in UW_CONTEXT the eh return target IP and data registers, which will
977    be restored with the others and retrieved by the landing pad once the jump
978    occurred.  */
979
980 static void
981 setup_to_install (_Unwind_Context *uw_context,
982                   _Unwind_Exception *uw_exception,
983                   _Unwind_Ptr uw_landing_pad,
984                   int uw_filter)
985 {
986 #ifndef EH_RETURN_DATA_REGNO
987   /* We should not be called if the appropriate underlying support is not
988      there.  */
989   abort ();
990 #else
991   /* 1/ exception object pointer, which might be provided back to
992      _Unwind_Resume (and thus to this personality routine) if we are jumping
993      to a cleanup.  */
994   _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (0),
995                  (_Unwind_Word)uw_exception);
996
997   /* 2/ handler switch value register, which will also be used by the target
998      landing pad to decide what action it shall take.  */
999   _Unwind_SetGR (uw_context, __builtin_eh_return_data_regno (1),
1000                  (_Unwind_Word)uw_filter);
1001
1002   /* Setup the address we should jump at to reach the code where there is the
1003      "something" we found.  */
1004   _Unwind_SetIP (uw_context, uw_landing_pad);
1005 #endif
1006 }
1007
1008 /* The following is defined from a-except.adb. Its purpose is to enable
1009    automatic backtraces upon exception raise, as provided through the
1010    GNAT.Traceback facilities.  */
1011 extern void __gnat_notify_handled_exception (void);
1012 extern void __gnat_notify_unhandled_exception (void);
1013
1014 /* Below is the eh personality routine per se. We currently assume that only
1015    GNU-Ada exceptions are met.  */
1016
1017 #ifdef __USING_SJLJ_EXCEPTIONS__
1018 #define PERSONALITY_FUNCTION    __gnat_eh_personality_sj
1019 #else
1020 #define PERSONALITY_FUNCTION    __gnat_eh_personality
1021 #endif
1022
1023 /* Major tweak for ia64-vms : the CHF propagation phase calls this personality
1024    routine with sigargs/mechargs arguments and has very specific expectations
1025    on possible return values.
1026
1027    We handle this with a number of specific tricks:
1028
1029    1. We tweak the personality routine prototype to have the "version" and
1030       "phases" two first arguments be void * instead of int and _Unwind_Action
1031       as nominally expected in the GCC context.
1032
1033       This allows us to access the full range of bits passed in every case and
1034       has no impact on the callers side since each argument remains assigned
1035       the same single 64bit slot.
1036
1037    2. We retrieve the corresponding int and _Unwind_Action values within the
1038       routine for regular use with truncating conversions. This is a noop when
1039       called from the libgcc unwinder.
1040
1041    3. We assume we're called by the VMS CHF when unexpected bits are set in
1042       both those values. The incoming arguments are then real sigargs and
1043       mechargs pointers, which we then redirect to __gnat_handle_vms_condition
1044       for proper processing.
1045 */
1046 #if defined (VMS) && defined (__IA64)
1047 typedef void * version_arg_t;
1048 typedef void * phases_arg_t;
1049 #else
1050 typedef int version_arg_t;
1051 typedef _Unwind_Action phases_arg_t;
1052 #endif
1053
1054 _Unwind_Reason_Code
1055 PERSONALITY_FUNCTION (version_arg_t version_arg,
1056                       phases_arg_t phases_arg,
1057                       _Unwind_Exception_Class uw_exception_class,
1058                       _Unwind_Exception *uw_exception,
1059                       _Unwind_Context *uw_context)
1060 {
1061   /* Fetch the version and phases args with their nominal ABI types for later
1062      use. This is a noop everywhere except on ia64-vms when called from the
1063      Condition Handling Facility.  */
1064   int uw_version = (int) version_arg;
1065   _Unwind_Action uw_phases = (_Unwind_Action) phases_arg;
1066
1067   _GNAT_Exception * gnat_exception = (_GNAT_Exception *) uw_exception;
1068
1069   region_descriptor region;
1070   action_descriptor action;
1071
1072   /* Check that we're called from the ABI context we expect, with a major
1073      possible variation on VMS for IA64.  */
1074   if (uw_version != 1)
1075     {
1076       #if defined (VMS) && defined (__IA64)
1077
1078       /* Assume we're called with sigargs/mechargs arguments if really
1079          unexpected bits are set in our first two formals.  Redirect to the
1080          GNAT condition handling code in this case.  */
1081
1082       extern long __gnat_handle_vms_condition (void *, void *);
1083
1084       unsigned int version_unexpected_bits_mask = 0xffffff00U;
1085       unsigned int phases_unexpected_bits_mask  = 0xffffff00U;
1086
1087       if ((unsigned int)uw_version & version_unexpected_bits_mask
1088           && (unsigned int)uw_phases & phases_unexpected_bits_mask)
1089         return __gnat_handle_vms_condition (version_arg, phases_arg);
1090       #endif
1091
1092       return _URC_FATAL_PHASE1_ERROR;
1093     }
1094
1095   db_indent (DB_INDENT_RESET);
1096   db_phases (uw_phases);
1097   db_indent (DB_INDENT_INCREASE);
1098
1099   /* Get the region description for the context we were provided with. This
1100      will tell us if there is some lsda, call_site, action and/or ttype data
1101      for the associated ip.  */
1102   get_region_description_for (uw_context, &region);
1103   db_region_for (&region, uw_context);
1104
1105   /* No LSDA => no handlers or cleanups => we shall unwind further up.  */
1106   if (! region.lsda)
1107     return _URC_CONTINUE_UNWIND;
1108
1109   /* Search the call-site and action-record tables for the action associated
1110      with this IP.  */
1111   get_action_description_for (uw_context, uw_exception, &region, &action);
1112   db_action_for (&action, uw_context);
1113
1114   /* Whatever the phase, if there is nothing relevant in this frame,
1115      unwinding should just go on.  */
1116   if (action.kind == nothing)
1117     return _URC_CONTINUE_UNWIND;
1118
1119   /* If we found something in search phase, we should return a code indicating
1120      what to do next depending on what we found. If we only have cleanups
1121      around, we shall try to unwind further up to find a handler, otherwise,
1122      tell we have a handler, which will trigger the second phase.  */
1123   if (uw_phases & _UA_SEARCH_PHASE)
1124     {
1125       if (action.kind == cleanup)
1126         {
1127           Adjust_N_Cleanups_For (gnat_exception, 1);
1128           return _URC_CONTINUE_UNWIND;
1129         }
1130       else
1131         {
1132           /* Trigger the appropriate notification routines before the second
1133              phase starts, which ensures the stack is still intact. */
1134           __gnat_notify_handled_exception ();
1135
1136           return _URC_HANDLER_FOUND;
1137         }
1138     }
1139
1140   /* We found something in cleanup/handler phase, which might be the handler
1141      or a cleanup for a handled occurrence, or a cleanup for an unhandled
1142      occurrence (we are in a FORCED_UNWIND phase in this case). Install the
1143      context to get there.  */
1144
1145   /* If we are going to install a cleanup context, decrement the cleanup
1146      count.  This is required in a FORCED_UNWINDing phase (for an unhandled
1147      exception), as this is used from the forced unwinding handler in
1148      Ada.Exceptions.Exception_Propagation to decide whether unwinding should
1149      proceed further or Unhandled_Exception_Terminate should be called.  */
1150   if (action.kind == cleanup)
1151     Adjust_N_Cleanups_For (gnat_exception, -1);
1152
1153   setup_to_install
1154     (uw_context, uw_exception, action.landing_pad, action.ttype_filter);
1155
1156   return _URC_INSTALL_CONTEXT;
1157 }
1158
1159 /* Define the consistently named wrappers imported by Propagate_Exception.  */
1160
1161 #ifdef __USING_SJLJ_EXCEPTIONS__
1162
1163 #undef _Unwind_RaiseException
1164
1165 _Unwind_Reason_Code
1166 __gnat_Unwind_RaiseException (_Unwind_Exception *e)
1167 {
1168   return _Unwind_SjLj_RaiseException (e);
1169 }
1170
1171
1172 #undef _Unwind_ForcedUnwind
1173
1174 _Unwind_Reason_Code
1175 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e,
1176                             void * handler,
1177                             void * argument)
1178 {
1179   return _Unwind_SjLj_ForcedUnwind (e, handler, argument);
1180 }
1181
1182
1183 #else /* __USING_SJLJ_EXCEPTIONS__ */
1184
1185 _Unwind_Reason_Code
1186 __gnat_Unwind_RaiseException (_Unwind_Exception *e)
1187 {
1188   return _Unwind_RaiseException (e);
1189 }
1190
1191 _Unwind_Reason_Code
1192 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e,
1193                             void * handler,
1194                             void * argument)
1195 {
1196   return _Unwind_ForcedUnwind (e, handler, argument);
1197 }
1198
1199 #endif /* __USING_SJLJ_EXCEPTIONS__ */
1200
1201 #else
1202 /* ! IN_RTS  */
1203
1204 /* Define the corresponding stubs for the compiler.  */
1205
1206 /* We don't want fancy_abort here.  */
1207 #undef abort
1208
1209 _Unwind_Reason_Code
1210 __gnat_Unwind_RaiseException (_Unwind_Exception *e ATTRIBUTE_UNUSED)
1211 {
1212   abort ();
1213 }
1214
1215
1216 _Unwind_Reason_Code
1217 __gnat_Unwind_ForcedUnwind (_Unwind_Exception *e ATTRIBUTE_UNUSED,
1218                             void * handler ATTRIBUTE_UNUSED,
1219                             void * argument ATTRIBUTE_UNUSED)
1220 {
1221   abort ();
1222 }
1223
1224 #endif /* IN_RTS */