Debian Codegraph @

gcc/ada/raise-gcc.c

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