1 // GNU D Compiler exception personality routines.
2 // Copyright (C) 2011-2022 Free Software Foundation, Inc.
3 
4 // GCC is free software; you can redistribute it and/or modify it under
5 // the terms of the GNU General Public License as published by the Free
6 // Software Foundation; either version 3, or (at your option) any later
7 // version.
8 
9 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
10 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 // for more details.
13 
14 // Under Section 7 of GPL version 3, you are granted additional
15 // permissions described in the GCC Runtime Library Exception, version
16 // 3.1, as published by the Free Software Foundation.
17 
18 // You should have received a copy of the GNU General Public License and
19 // a copy of the GCC Runtime Library Exception along with this program;
20 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
21 // <http://www.gnu.org/licenses/>.
22 
23 // This code is based on the libstdc++ exception handling routines.
24 
25 module gcc.deh;
26 
27 import gcc.unwind;
28 import gcc.unwind.pe;
29 import gcc.builtins;
30 import gcc.config;
31 import gcc.attributes;
32 
33 extern(C)
34 {
35     int _d_isbaseof(ClassInfo, ClassInfo) @nogc nothrow pure @safe;
36     void _d_createTrace(Throwable, void*);
37     void _d_print_throwable(Throwable t);
38 }
39 
40 /**
41  * Declare all known and handled exception classes.
42  * D exceptions -- "GNUCD\0\0\0".
43  * C++ exceptions -- "GNUCC++\0"
44  * C++ dependent exceptions -- "GNUCC++\x01"
45  */
46 static if (GNU_ARM_EABI_Unwinder)
47 {
48     enum _Unwind_Exception_Class gdcExceptionClass = "GNUCD\0\0\0";
49     enum _Unwind_Exception_Class gxxExceptionClass = "GNUCC++\0";
50     enum _Unwind_Exception_Class gxxDependentExceptionClass = "GNUCC++\x01";
51 }
52 else
53 {
54     enum _Unwind_Exception_Class gdcExceptionClass =
55         (cast(_Unwind_Exception_Class)'G' << 56) |
56         (cast(_Unwind_Exception_Class)'N' << 48) |
57         (cast(_Unwind_Exception_Class)'U' << 40) |
58         (cast(_Unwind_Exception_Class)'C' << 32) |
59         (cast(_Unwind_Exception_Class)'D' << 24);
60 
61     enum _Unwind_Exception_Class gxxExceptionClass =
62         (cast(_Unwind_Exception_Class)'G' << 56) |
63         (cast(_Unwind_Exception_Class)'N' << 48) |
64         (cast(_Unwind_Exception_Class)'U' << 40) |
65         (cast(_Unwind_Exception_Class)'C' << 32) |
66         (cast(_Unwind_Exception_Class)'C' << 24) |
67         (cast(_Unwind_Exception_Class)'+' << 16) |
68         (cast(_Unwind_Exception_Class)'+' <<  8) |
69         (cast(_Unwind_Exception_Class)0 <<  0);
70 
71     enum _Unwind_Exception_Class gxxDependentExceptionClass =
72         gxxExceptionClass + 1;
73 }
74 
75 /**
76  * Checks for GDC exception class.
77  */
isGdcExceptionClass(_Unwind_Exception_Class c)78 bool isGdcExceptionClass(_Unwind_Exception_Class c) @nogc
79 {
80     static if (GNU_ARM_EABI_Unwinder)
81     {
82         return c[0] == gdcExceptionClass[0]
83             && c[1] == gdcExceptionClass[1]
84             && c[2] == gdcExceptionClass[2]
85             && c[3] == gdcExceptionClass[3]
86             && c[4] == gdcExceptionClass[4]
87             && c[5] == gdcExceptionClass[5]
88             && c[6] == gdcExceptionClass[6]
89             && c[7] == gdcExceptionClass[7];
90     }
91     else
92     {
93         return c == gdcExceptionClass;
94     }
95 }
96 
97 /**
98  * Checks for any C++ exception class.
99  */
isGxxExceptionClass(_Unwind_Exception_Class c)100 bool isGxxExceptionClass(_Unwind_Exception_Class c) @nogc
101 {
102     static if (GNU_ARM_EABI_Unwinder)
103     {
104         return c[0] == gxxExceptionClass[0]
105             && c[1] == gxxExceptionClass[1]
106             && c[2] == gxxExceptionClass[2]
107             && c[3] == gxxExceptionClass[3]
108             && c[4] == gxxExceptionClass[4]
109             && c[5] == gxxExceptionClass[5]
110             && c[6] == gxxExceptionClass[6]
111             && (c[7] == gxxExceptionClass[7]
112                 || c[7] == gxxDependentExceptionClass[7]);
113     }
114     else
115     {
116         return c == gxxExceptionClass
117             || c == gxxDependentExceptionClass;
118     }
119 }
120 
121 /**
122  * Checks for primary or dependent, but not that it is a C++ exception.
123  */
isDependentException(_Unwind_Exception_Class c)124 bool isDependentException(_Unwind_Exception_Class c) @nogc
125 {
126     static if (GNU_ARM_EABI_Unwinder)
127         return (c[7] == '\x01');
128     else
129         return (c & 1);
130 }
131 
132 /**
133  * A D exception object consists of a header, which is a wrapper
134  * around an unwind object header with additional D specific
135  * information, prefixed by the exception object itself.
136  */
137 struct ExceptionHeader
138 {
139     // Because of a lack of __aligned__ style attribute, our object
140     // and the unwind object are the first two fields.
141     static if (Throwable.alignof < _Unwind_Exception.alignof)
142         ubyte[_Unwind_Exception.alignof - Throwable.alignof] pad;
143 
144     // The object being thrown.  The compiled code expects this to
145     // be immediately before the generic exception header.
146     Throwable object;
147 
148     // The generic exception header.
149     _Unwind_Exception unwindHeader;
150 
151     static assert(unwindHeader.offsetof - object.offsetof == object.sizeof);
152 
153     // Cache handler details between Phase 1 and Phase 2.
154     static if (GNU_ARM_EABI_Unwinder)
155     {
156         // Nothing here yet.
157     }
158     else
159     {
160         // Which catch was found.
161         int handler;
162 
163         // Language Specific Data Area for function enclosing the handler.
164         const(ubyte)* languageSpecificData;
165 
166         // Pointer to catch code.
167         _Unwind_Ptr landingPad;
168 
169         // Canonical Frame Address (CFA) for the enclosing handler.
170         _Unwind_Word canonicalFrameAddress;
171     }
172 
173     // Stack other thrown exceptions in current thread through here.
174     ExceptionHeader* next;
175 
176     // Thread local stack of chained exceptions.
177     static ExceptionHeader* stack;
178 
179     // Pre-allocate storage for 1 instance per thread.
180     // Use calloc/free for multiple exceptions in flight.
181     static ExceptionHeader ehstorage;
182 
183     /**
184      * Allocate and initialize an ExceptionHeader.
185      */
createExceptionHeader186     static ExceptionHeader* create(Throwable o) @nogc
187     {
188         auto eh = &ehstorage;
189 
190         // Check exception object in use.
191         if (eh.object)
192         {
193             eh = cast(ExceptionHeader*) __builtin_calloc(ExceptionHeader.sizeof, 1);
194             // Out of memory while throwing - not much else can be done.
195             if (!eh)
196                 terminate("out of memory", __LINE__);
197         }
198         eh.object = o;
199 
200         eh.unwindHeader.exception_class = gdcExceptionClass;
201 
202         return eh;
203     }
204 
205     /**
206      * Free ExceptionHeader that was created by create().
207      */
freeExceptionHeader208     static void free(ExceptionHeader* eh) @nogc
209     {
210         __builtin_memset(eh, 0, ExceptionHeader.sizeof);
211         if (eh != &ehstorage)
212             __builtin_free(eh);
213     }
214 
215     /**
216      * Push this onto stack of chained exceptions.
217      */
pushExceptionHeader218     void push() @nogc
219     {
220         next = stack;
221         stack = &this;
222     }
223 
224     /**
225      * Pop and return top of chained exception stack.
226      */
popExceptionHeader227     static ExceptionHeader* pop() @nogc
228     {
229         auto eh = stack;
230         stack = eh.next;
231         return eh;
232     }
233 
234     /**
235      * Save stage1 handler information in the exception object.
236      */
saveExceptionHeader237     static void save(_Unwind_Exception* unwindHeader,
238                      _Unwind_Word cfa, int handler,
239                      const(ubyte)* lsda, _Unwind_Ptr landingPad) @nogc
240     {
241         static if (GNU_ARM_EABI_Unwinder)
242         {
243             unwindHeader.barrier_cache.sp = cfa;
244             unwindHeader.barrier_cache.bitpattern[1] = cast(_uw)handler;
245             unwindHeader.barrier_cache.bitpattern[2] = cast(_uw)lsda;
246             unwindHeader.barrier_cache.bitpattern[3] = cast(_uw)landingPad;
247         }
248         else
249         {
250             ExceptionHeader* eh = toExceptionHeader(unwindHeader);
251             eh.canonicalFrameAddress = cfa;
252             eh.handler = handler;
253             eh.languageSpecificData = lsda;
254             eh.landingPad = landingPad;
255         }
256     }
257 
258     /**
259      * Restore the catch handler data saved during phase1.
260      */
restoreExceptionHeader261     static void restore(_Unwind_Exception* unwindHeader, out int handler,
262                         out const(ubyte)* lsda, out _Unwind_Ptr landingPad,
263                         out _Unwind_Word cfa) @nogc
264     {
265         static if (GNU_ARM_EABI_Unwinder)
266         {
267             cfa = unwindHeader.barrier_cache.sp;
268             handler = cast(int)unwindHeader.barrier_cache.bitpattern[1];
269             lsda = cast(ubyte*)unwindHeader.barrier_cache.bitpattern[2];
270             landingPad = cast(_Unwind_Ptr)unwindHeader.barrier_cache.bitpattern[3];
271         }
272         else
273         {
274             ExceptionHeader* eh = toExceptionHeader(unwindHeader);
275             cfa = eh.canonicalFrameAddress;
276             handler = eh.handler;
277             lsda = eh.languageSpecificData;
278             landingPad = cast(_Unwind_Ptr)eh.landingPad;
279         }
280     }
281 
282     /**
283      * Convert from pointer to unwindHeader to pointer to ExceptionHeader
284      * that it is embedded inside of.
285      */
toExceptionHeaderExceptionHeader286     static ExceptionHeader* toExceptionHeader(_Unwind_Exception* exc) @nogc
287     {
288         return cast(ExceptionHeader*)(cast(void*)exc - ExceptionHeader.unwindHeader.offsetof);
289     }
290 }
291 
292 /**
293  * Map to C++ std::type_info's virtual functions from D,
294  * being careful to not require linking with libstdc++.
295  * So it is given a different name.
296  */
297 extern(C++) interface CxxTypeInfo
298 {
299     void dtor1();
300     void dtor2();
301     bool __is_pointer_p() const;
302     bool __is_function_p() const;
303     bool __do_catch(const CxxTypeInfo, void**, uint) const;
304     bool __do_upcast(const void*, void**) const;
305 }
306 
307 /**
308  * Structure of a C++ exception, represented as a C structure.
309  * See unwind-cxx.h for the full definition.
310  */
311 struct CxaExceptionHeader
312 {
313     union
314     {
315         CxxTypeInfo exceptionType;
316         void* primaryException;
317     }
318     void function(void*) exceptionDestructor;
319     void function() unexpectedHandler;
320     void function() terminateHandler;
321     CxaExceptionHeader* nextException;
322     int handlerCount;
323 
324     static if (GNU_ARM_EABI_Unwinder)
325     {
326         CxaExceptionHeader* nextPropagatingException;
327         int propagationCount;
328     }
329     else
330     {
331         int handlerSwitchValue;
332         const(ubyte)* actionRecord;
333         const(ubyte)* languageSpecificData;
334         _Unwind_Ptr catchTemp;
335         void* adjustedPtr;
336     }
337 
338     _Unwind_Exception unwindHeader;
339 
340     /**
341      * There's no saving between phases, so only cache pointer.
342      * __cxa_begin_catch expects this to be set.
343      */
saveCxaExceptionHeader344     static void save(_Unwind_Exception* unwindHeader, void* thrownPtr) @nogc
345     {
346         static if (GNU_ARM_EABI_Unwinder)
347             unwindHeader.barrier_cache.bitpattern[0] = cast(_uw) thrownPtr;
348         else
349         {
350             auto eh = toExceptionHeader(unwindHeader);
351             eh.adjustedPtr = thrownPtr;
352         }
353     }
354 
355     /**
356      * Get pointer to the thrown object if the thrown object type behind the
357      * exception is implicitly convertible to the catch type.
358      */
getAdjustedPtrCxaExceptionHeader359     static void* getAdjustedPtr(_Unwind_Exception* exc, CxxTypeInfo catchType)
360     {
361         void* thrownPtr;
362 
363         // A dependent C++ exceptions is just a wrapper around the unwind header.
364         // A primary C++ exception has the thrown object located immediately after it.
365         if (isDependentException(exc.exception_class))
366             thrownPtr = toExceptionHeader(exc).primaryException;
367         else
368             thrownPtr = cast(void*)(exc + 1);
369 
370         // Pointer types need to adjust the actual pointer, not the pointer that is
371         // the exception object.  This also has the effect of passing pointer types
372         // "by value" through the __cxa_begin_catch return value.
373         const throw_type = (cast(CxaExceptionHeader*)thrownPtr - 1).exceptionType;
374 
375         if (throw_type.__is_pointer_p())
376             thrownPtr = *cast(void**)thrownPtr;
377 
378         // Pointer adjustment may be necessary due to multiple inheritance
379         if (catchType is throw_type
380             || catchType.__do_catch(throw_type, &thrownPtr, 1))
381             return thrownPtr;
382 
383         return null;
384     }
385 
386     /**
387      * Convert from pointer to unwindHeader to pointer to CxaExceptionHeader
388      * that it is embedded inside of.
389      */
toExceptionHeaderCxaExceptionHeader390     static CxaExceptionHeader* toExceptionHeader(_Unwind_Exception* exc) @nogc
391     {
392         return cast(CxaExceptionHeader*)(exc + 1) - 1;
393     }
394 }
395 
396 /**
397  * Called if exception handling must be abandoned for any reason.
398  */
terminate(string msg,uint line)399 private void terminate(string msg, uint line) @nogc
400 {
401     import core.stdc.stdio;
402     import core.stdc.stdlib;
403 
404     static bool terminating;
405     if (terminating)
406     {
407         fputs("terminate called recursively\n", stderr);
408         abort();
409     }
410     terminating = true;
411 
412     fprintf(stderr, "gcc.deh(%u): %.*s\n", line, cast(int)msg.length, msg.ptr);
413 
414     abort();
415 }
416 
417 /**
418  * Called when fibers switch contexts.
419  */
_d_eh_swapContext(void * newContext)420 extern(C) void* _d_eh_swapContext(void* newContext) nothrow @nogc
421 {
422     auto old = ExceptionHeader.stack;
423     ExceptionHeader.stack = cast(ExceptionHeader*)newContext;
424     return old;
425 }
426 
427 /**
428  * Called before starting a catch.  Returns the exception object.
429  */
__gdc_begin_catch(_Unwind_Exception * unwindHeader)430 extern(C) void* __gdc_begin_catch(_Unwind_Exception* unwindHeader)
431 {
432     ExceptionHeader* header = ExceptionHeader.toExceptionHeader(unwindHeader);
433 
434     void* objectp = cast(void*)header.object;
435     // Remove our reference to the exception. We should not decrease its refcount,
436     // because we pass the object on to the caller.
437     header.object = null;
438 
439     // Something went wrong when stacking up chained headers...
440     if (header != ExceptionHeader.pop())
441         terminate("catch error", __LINE__);
442 
443     // Handling for this exception is complete.
444     _Unwind_DeleteException(&header.unwindHeader);
445 
446     return objectp;
447 }
448 
449 /**
450  * Perform a throw, D style. Throw will unwind through this call,
451  * so there better not be any handlers or exception thrown here.
452  */
_d_throw(Throwable object)453 extern(C) void _d_throw(Throwable object)
454 {
455     // If possible, avoid always allocating new memory for exception headers.
456     ExceptionHeader *eh = ExceptionHeader.create(object);
457 
458     // Add to thrown exception stack.
459     eh.push();
460 
461     // Increment reference count if object is a refcounted Throwable.
462     auto refcount = object.refcount();
463     if (refcount)
464         object.refcount() = refcount + 1;
465 
466     // Called by unwinder when exception object needs destruction by other than our code.
467     extern(C) void exception_cleanup(_Unwind_Reason_Code code, _Unwind_Exception* exc)
468     {
469         // If we haven't been caught by a foreign handler, then this is
470         // some sort of unwind error.  In that case just die immediately.
471         // _Unwind_DeleteException in the HP-UX IA64 libunwind library
472         //  returns _URC_NO_REASON and not _URC_FOREIGN_EXCEPTION_CAUGHT
473         // like the GCC _Unwind_DeleteException function does.
474         if (code != _URC_FOREIGN_EXCEPTION_CAUGHT && code != _URC_NO_REASON)
475             terminate("uncaught exception", __LINE__);
476 
477         auto eh = ExceptionHeader.toExceptionHeader(exc);
478         ExceptionHeader.free(eh);
479     }
480 
481     eh.unwindHeader.exception_cleanup = &exception_cleanup;
482 
483     // Runtime now expects us to do this first before unwinding.
484     _d_createTrace(eh.object, null);
485 
486     // We're happy with setjmp/longjmp exceptions or region-based
487     // exception handlers: entry points are provided here for both.
488     _Unwind_Reason_Code r = void;
489 
490     version (GNU_SjLj_Exceptions)
491         r = _Unwind_SjLj_RaiseException(&eh.unwindHeader);
492     else
493         r = _Unwind_RaiseException(&eh.unwindHeader);
494 
495     // If code == _URC_END_OF_STACK, then we reached top of stack without finding
496     // a handler for the exception.  Since each thread is run in a try/catch,
497     // this oughtn't happen.  If code is something else, we encountered some sort
498     // of heinous lossage from which we could not recover.  As is the way of such
499     // things, almost certainly we will have crashed before now, rather than
500     // actually being able to diagnose the problem.
501     if (r == _URC_END_OF_STACK)
502     {
503         __gdc_begin_catch(&eh.unwindHeader);
504         _d_print_throwable(object);
505         terminate("uncaught exception", __LINE__);
506     }
507 
508     terminate("unwind error", __LINE__);
509 }
510 
511 static if (GNU_ARM_EABI_Unwinder)
512 {
513     enum personality_fn_attributes = attribute("target", ("general-regs-only"));
514 }
515 else
516 {
517     enum personality_fn_attributes = "";
518 }
519 
520 /**
521  * Read and extract information from the LSDA (.gcc_except_table section).
522  */
523 @personality_fn_attributes
scanLSDA(const (ubyte)* lsda,_Unwind_Exception_Class exceptionClass,_Unwind_Action actions,_Unwind_Exception * unwindHeader,_Unwind_Context * context,_Unwind_Word cfa,out _Unwind_Ptr landingPad,out int handler)524 _Unwind_Reason_Code scanLSDA(const(ubyte)* lsda, _Unwind_Exception_Class exceptionClass,
525                              _Unwind_Action actions, _Unwind_Exception* unwindHeader,
526                              _Unwind_Context* context, _Unwind_Word cfa,
527                              out _Unwind_Ptr landingPad, out int handler)
528 {
529     // If no LSDA, then there are no handlers or cleanups.
530     if (lsda is null)
531         return CONTINUE_UNWINDING(unwindHeader, context);
532 
533     // Parse the LSDA header
534     auto p = lsda;
535 
536     auto Start = (context ? _Unwind_GetRegionStart(context) : 0);
537 
538     // Find @LPStart, the base to which landing pad offsets are relative.
539     ubyte LPStartEncoding = *p++;
540     _Unwind_Ptr LPStart = 0;
541 
542     if (LPStartEncoding != DW_EH_PE_omit)
543         LPStart = read_encoded_value(context, LPStartEncoding, p);
544     else
545         LPStart = Start;
546 
547     // Find @TType, the base of the handler and exception spec type data.
548     ubyte TTypeEncoding = *p++;
549     const(ubyte)* TType = null;
550 
551     if (TTypeEncoding != DW_EH_PE_omit)
552     {
553         static if (__traits(compiles, _TTYPE_ENCODING))
554         {
555             // Older ARM EABI toolchains set this value incorrectly, so use a
556             // hardcoded OS-specific format.
557             TTypeEncoding = _TTYPE_ENCODING;
558         }
559         auto TTbase = read_uleb128(p);
560         TType = p + TTbase;
561     }
562 
563     // The encoding and length of the call-site table; the action table
564     // immediately follows.
565     ubyte CSEncoding = *p++;
566     auto CSTableSize = read_uleb128(p);
567     const(ubyte)* actionTable = p + CSTableSize;
568 
569     auto TTypeBase = base_of_encoded_value(TTypeEncoding, context);
570 
571     // Get instruction pointer (ip) at start of instruction that threw.
572     version (CRuntime_Glibc)
573     {
574         int ip_before_insn;
575         auto ip = _Unwind_GetIPInfo(context, &ip_before_insn);
576         if (!ip_before_insn)
577             --ip;
578     }
579     else
580     {
581         auto ip = _Unwind_GetIP(context);
582         --ip;
583     }
584 
585     bool saw_cleanup = false;
586     bool saw_handler = false;
587     const(ubyte)* actionRecord = null;
588 
589     version (GNU_SjLj_Exceptions)
590     {
591         // The given "IP" is an index into the call-site table, with two
592         // exceptions -- -1 means no-action, and 0 means terminate.
593         // But since we're using uleb128 values, we've not got random
594         // access to the array.
595         if (cast(int) ip <= 0)
596         {
597             return _URC_CONTINUE_UNWIND;
598         }
599         else
600         {
601             _uleb128_t CSLandingPad, CSAction;
602             do
603             {
604                 CSLandingPad = read_uleb128(p);
605                 CSAction = read_uleb128(p);
606             }
607             while (--ip);
608 
609             // Can never have null landing pad for sjlj -- that would have
610             // been indicated by a -1 call site index.
611             landingPad = CSLandingPad + 1;
612             if (CSAction)
613                 actionRecord = actionTable + CSAction - 1;
614         }
615     }
616     else
617     {
618         // Search the call-site table for the action associated with this IP.
619         while (p < actionTable)
620         {
621             // Note that all call-site encodings are "absolute" displacements.
622             auto CSStart = read_encoded_value(null, CSEncoding, p);
623             auto CSLen = read_encoded_value(null, CSEncoding, p);
624             auto CSLandingPad = read_encoded_value(null, CSEncoding, p);
625             auto CSAction = read_uleb128(p);
626 
627             // The table is sorted, so if we've passed the ip, stop.
628             if (ip < Start + CSStart)
629                 p = actionTable;
630             else if (ip < Start + CSStart + CSLen)
631             {
632                 if (CSLandingPad)
633                     landingPad = LPStart + CSLandingPad;
634                 if (CSAction)
635                     actionRecord = actionTable + CSAction - 1;
636                 break;
637             }
638         }
639     }
640 
641     if (landingPad == 0)
642     {
643         // IP is present, but has a null landing pad.
644         // No cleanups or handlers to be run.
645     }
646     else if (actionRecord is null)
647     {
648         // If ip is present, has a non-null landing pad, and a null
649         // action table offset, then there are only cleanups present.
650         // Cleanups use a zero switch value, as set above.
651         saw_cleanup = true;
652     }
653     else
654     {
655         // Otherwise we have a catch handler or exception specification.
656         handler = actionTableLookup(actions, unwindHeader, actionRecord,
657                                     lsda, exceptionClass, TTypeBase,
658                                     TType, TTypeEncoding,
659                                     saw_handler, saw_cleanup);
660     }
661 
662     // IP is not in table.  No associated cleanups.
663     if (!saw_handler && !saw_cleanup)
664         return CONTINUE_UNWINDING(unwindHeader, context);
665 
666     if (actions & _UA_SEARCH_PHASE)
667     {
668         if (!saw_handler)
669             return CONTINUE_UNWINDING(unwindHeader, context);
670 
671         // For domestic exceptions, we cache data from phase 1 for phase 2.
672         if (isGdcExceptionClass(exceptionClass))
673             ExceptionHeader.save(unwindHeader, cfa, handler, lsda, landingPad);
674 
675         return _URC_HANDLER_FOUND;
676     }
677 
678     return 0;
679 }
680 
681 /**
682  * Look up and return the handler index of the classType in Action Table.
683  */
actionTableLookup(_Unwind_Action actions,_Unwind_Exception * unwindHeader,const (ubyte)* actionRecord,const (ubyte)* lsda,_Unwind_Exception_Class exceptionClass,_Unwind_Ptr TTypeBase,const (ubyte)* TType,ubyte TTypeEncoding,out bool saw_handler,out bool saw_cleanup)684 int actionTableLookup(_Unwind_Action actions, _Unwind_Exception* unwindHeader,
685                       const(ubyte)* actionRecord, const(ubyte)* lsda,
686                       _Unwind_Exception_Class exceptionClass,
687                       _Unwind_Ptr TTypeBase, const(ubyte)* TType,
688                       ubyte TTypeEncoding,
689                       out bool saw_handler, out bool saw_cleanup)
690 {
691     ClassInfo thrownType;
692     if (isGdcExceptionClass(exceptionClass))
693     {
694         thrownType = getClassInfo(unwindHeader, lsda);
695     }
696 
697     while (1)
698     {
699         auto ap = actionRecord;
700         auto ARFilter = read_sleb128(ap);
701         auto apn = ap;
702         auto ARDisp = read_sleb128(ap);
703 
704         if (ARFilter == 0)
705         {
706             // Zero filter values are cleanups.
707             saw_cleanup = true;
708         }
709         else if (actions & _UA_FORCE_UNWIND)
710         {
711             // During forced unwinding, we only run cleanups.
712         }
713         else if (ARFilter > 0)
714         {
715             // Positive filter values are handlers.
716             auto encodedSize = size_of_encoded_value(TTypeEncoding);
717 
718             // ARFilter is the negative index from TType, which is where
719             // the ClassInfo is stored.
720             const(ubyte)* tp = TType - ARFilter * encodedSize;
721 
722             auto entry = read_encoded_value_with_base(TTypeEncoding, TTypeBase, tp);
723             ClassInfo ci = cast(ClassInfo)cast(void*)(entry);
724 
725             // D does not have catch-all handlers, and so the following
726             // assumes that we will never handle a null value.
727             assert(ci !is null);
728 
729             if (ci.classinfo is __cpp_type_info_ptr.classinfo
730                 && isGxxExceptionClass(exceptionClass))
731             {
732                 // catchType is the catch clause type_info.
733                 auto catchType = cast(CxxTypeInfo)((cast(__cpp_type_info_ptr)cast(void*)ci).ptr);
734                 auto thrownPtr = CxaExceptionHeader.getAdjustedPtr(unwindHeader, catchType);
735 
736                 if (thrownPtr !is null)
737                 {
738                     if (actions & _UA_SEARCH_PHASE)
739                         CxaExceptionHeader.save(unwindHeader, thrownPtr);
740                     saw_handler = true;
741                     return cast(int)ARFilter;
742                 }
743             }
744             else if (isGdcExceptionClass(exceptionClass)
745                      && _d_isbaseof(thrownType, ci))
746             {
747                 saw_handler = true;
748                 return cast(int)ARFilter;
749             }
750             else
751             {
752                 // ??? What to do about other GNU language exceptions.
753             }
754         }
755         else
756         {
757             // Negative filter values are exception specifications,
758             // which D does not use.
759             break;
760         }
761 
762         if (ARDisp == 0)
763             break;
764         actionRecord = apn + ARDisp;
765     }
766 
767     return 0;
768 }
769 
770 /**
771  * Look at the chain of inflight exceptions and pick the class type that'll
772  * be looked for in catch clauses.
773  */
getClassInfo(_Unwind_Exception * unwindHeader,const (ubyte)* currentLsd)774 ClassInfo getClassInfo(_Unwind_Exception* unwindHeader,
775                        const(ubyte)* currentLsd) @nogc
776 {
777     ExceptionHeader* eh = ExceptionHeader.toExceptionHeader(unwindHeader);
778     // The first thrown Exception at the top of the stack takes precedence
779     // over others that are inflight, unless an Error was thrown, in which
780     // case, we search for error handlers instead.
781     Throwable ehobject = eh.object;
782     for (ExceptionHeader* ehn = eh.next; ehn; ehn = ehn.next)
783     {
784         const(ubyte)* nextLsd = void;
785         _Unwind_Ptr nextLandingPad = void;
786         _Unwind_Word nextCfa = void;
787         int nextHandler = void;
788 
789         ExceptionHeader.restore(&ehn.unwindHeader, nextHandler, nextLsd, nextLandingPad, nextCfa);
790 
791         // Don't combine when the exceptions are from different functions.
792         if (currentLsd != nextLsd)
793             break;
794 
795         Error e = cast(Error)ehobject;
796         if (e is null || (cast(Error)ehn.object) !is null)
797         {
798             currentLsd = nextLsd;
799             ehobject = ehn.object;
800         }
801     }
802     return ehobject.classinfo;
803 }
804 
805 /**
806  * Called when the personality function has found neither a cleanup or handler.
807  * To support ARM EABI personality routines, that must also unwind the stack.
808  */
809 @personality_fn_attributes
CONTINUE_UNWINDING(_Unwind_Exception * unwindHeader,_Unwind_Context * context)810 _Unwind_Reason_Code CONTINUE_UNWINDING(_Unwind_Exception* unwindHeader, _Unwind_Context* context)
811 {
812     static if (GNU_ARM_EABI_Unwinder)
813     {
814         if (__gnu_unwind_frame(unwindHeader, context) != _URC_OK)
815             return _URC_FAILURE;
816     }
817     return _URC_CONTINUE_UNWIND;
818 }
819 
820 /**
821  * Using a different personality function name causes link failures
822  * when trying to mix code using different exception handling models.
823  */
version(GNU_SEH_Exceptions)824 version (GNU_SEH_Exceptions)
825 {
826     enum PERSONALITY_FUNCTION = "__gdc_personality_imp";
827 
828     extern(C) EXCEPTION_DISPOSITION __gdc_personality_seh0(void* ms_exc, void* this_frame,
829                                                            void* ms_orig_context, void* ms_disp)
830     {
831         return _GCC_specific_handler(ms_exc, this_frame, ms_orig_context,
832                                      ms_disp, &gdc_personality);
833     }
834 }
version(GNU_SjLj_Exceptions)835 else version (GNU_SjLj_Exceptions)
836 {
837     enum PERSONALITY_FUNCTION = "__gdc_personality_sj0";
838 
839     private int __builtin_eh_return_data_regno(int x) { return x; }
840 }
841 else
842 {
843     enum PERSONALITY_FUNCTION = "__gdc_personality_v0";
844 }
845 
846 /**
847  * The "personality" function, specific to each language.
848  */
849 static if (GNU_ARM_EABI_Unwinder)
850 {
pragma(mangle,PERSONALITY_FUNCTION)851     pragma(mangle, PERSONALITY_FUNCTION)
852     @personality_fn_attributes
853     extern(C) _Unwind_Reason_Code gdc_personality(_Unwind_State state,
854                                                   _Unwind_Exception* unwindHeader,
855                                                   _Unwind_Context* context)
856     {
857         _Unwind_Action actions;
858 
859         switch (state & _US_ACTION_MASK)
860         {
861             case _US_VIRTUAL_UNWIND_FRAME:
862                 // If the unwind state pattern is (_US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND)
863                 // then we don't need to search for any handler as it is not a real exception.
864                 // Just unwind the stack.
865                 if (state & _US_FORCE_UNWIND)
866                     return CONTINUE_UNWINDING(unwindHeader, context);
867                 actions = _UA_SEARCH_PHASE;
868                 break;
869 
870             case _US_UNWIND_FRAME_STARTING:
871                 actions = _UA_CLEANUP_PHASE;
872                 if (!(state & _US_FORCE_UNWIND)
873                     && unwindHeader.barrier_cache.sp == _Unwind_GetGR(context, UNWIND_STACK_REG))
874                     actions |= _UA_HANDLER_FRAME;
875                 break;
876 
877             case _US_UNWIND_FRAME_RESUME:
878                 return CONTINUE_UNWINDING(unwindHeader, context);
879 
880             default:
881                 terminate("unwind error", __LINE__);
882         }
883         actions |= state & _US_FORCE_UNWIND;
884 
885         // The dwarf unwinder assumes the context structure holds things like
886         // the function and LSDA pointers.  The ARM implementation caches these
887         // in the exception header (UCB).  To avoid rewriting everything we make
888         // the virtual IP register point at the UCB.
889         _Unwind_SetGR(context, UNWIND_POINTER_REG, cast(_Unwind_Ptr)unwindHeader);
890 
891         return __gdc_personality(actions, unwindHeader.exception_class,
892                                  unwindHeader, context);
893     }
894 }
895 else
896 {
pragma(mangle,PERSONALITY_FUNCTION)897     pragma(mangle, PERSONALITY_FUNCTION)
898     extern(C) _Unwind_Reason_Code gdc_personality(int iversion,
899                                                   _Unwind_Action actions,
900                                                   _Unwind_Exception_Class exceptionClass,
901                                                   _Unwind_Exception* unwindHeader,
902                                                   _Unwind_Context* context)
903     {
904         // Interface version check.
905         if (iversion != 1)
906             return _URC_FATAL_PHASE1_ERROR;
907 
908         return __gdc_personality(actions, exceptionClass, unwindHeader, context);
909     }
910 }
911 
912 @personality_fn_attributes
__gdc_personality(_Unwind_Action actions,_Unwind_Exception_Class exceptionClass,_Unwind_Exception * unwindHeader,_Unwind_Context * context)913 private _Unwind_Reason_Code __gdc_personality(_Unwind_Action actions,
914                                               _Unwind_Exception_Class exceptionClass,
915                                               _Unwind_Exception* unwindHeader,
916                                               _Unwind_Context* context)
917 {
918     const(ubyte)* lsda;
919     _Unwind_Ptr landingPad;
920     _Unwind_Word cfa;
921     int handler;
922 
923     // Shortcut for phase 2 found handler for domestic exception.
924     if (actions == (_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME)
925         && isGdcExceptionClass(exceptionClass))
926     {
927         ExceptionHeader.restore(unwindHeader, handler, lsda, landingPad, cfa);
928         // Shouldn't have cached a null landing pad in phase 1.
929         if (landingPad == 0)
930             terminate("unwind error", __LINE__);
931     }
932     else
933     {
934         lsda = cast(ubyte*)_Unwind_GetLanguageSpecificData(context);
935 
936         static if (GNU_ARM_EABI_Unwinder)
937             cfa = _Unwind_GetGR(context, UNWIND_STACK_REG);
938         else
939             cfa = _Unwind_GetCFA(context);
940 
941         auto result = scanLSDA(lsda, exceptionClass, actions, unwindHeader,
942                                context, cfa, landingPad, handler);
943 
944         // Positive on handler found in phase 1, continue unwinding, or failure.
945         if (result)
946             return result;
947     }
948 
949     // Unexpected negative handler, call terminate directly.
950     if (handler < 0)
951         terminate("unwind error", __LINE__);
952 
953     // We can't use any of the deh routines with foreign exceptions,
954     // because they all expect unwindHeader to be an ExceptionHeader.
955     if (isGdcExceptionClass(exceptionClass))
956     {
957         // If there are any in-flight exceptions being thrown, chain our
958         // current object onto the end of the prevous object.
959         ExceptionHeader* eh = ExceptionHeader.toExceptionHeader(unwindHeader);
960         auto currentLsd = lsda;
961         bool bypassed = false;
962 
963         while (eh.next)
964         {
965             ExceptionHeader* ehn = eh.next;
966             const(ubyte)* nextLsd = void;
967             _Unwind_Ptr nextLandingPad = void;
968             _Unwind_Word nextCfa = void;
969             int nextHandler = void;
970 
971             ExceptionHeader.restore(&ehn.unwindHeader, nextHandler, nextLsd, nextLandingPad, nextCfa);
972 
973             Error e = cast(Error)eh.object;
974             if (e !is null && !cast(Error)ehn.object)
975             {
976                 // We found an Error, bypass the exception chain.
977                 currentLsd = nextLsd;
978                 eh = ehn;
979                 bypassed = true;
980                 continue;
981             }
982 
983             // Don't combine when the exceptions are from different functions.
984             if (currentLsd != nextLsd)
985                 break;
986 
987             // Add our object onto the end of the existing chain and replace
988             // our exception object with in-flight one.
989             eh.object = Throwable.chainTogether(ehn.object, eh.object);
990 
991             if (nextHandler != handler && !bypassed)
992             {
993                 handler = nextHandler;
994                 ExceptionHeader.save(unwindHeader, cfa, handler, lsda, landingPad);
995             }
996 
997             // Exceptions chained, can now throw away the previous header.
998             eh.next = ehn.next;
999             _Unwind_DeleteException(&ehn.unwindHeader);
1000         }
1001 
1002         if (bypassed)
1003         {
1004             eh = ExceptionHeader.toExceptionHeader(unwindHeader);
1005             Error e = cast(Error)eh.object;
1006             auto ehn = eh.next;
1007             e.bypassedException = ehn.object;
1008             eh.next = ehn.next;
1009             _Unwind_DeleteException(&ehn.unwindHeader);
1010         }
1011     }
1012 
1013     // Set up registers and jump to cleanup or handler.
1014     // For targets with pointers smaller than the word size, we must extend the
1015     // pointer, and this extension is target dependent.
1016     _Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
1017                   cast(_Unwind_Ptr)unwindHeader);
1018     _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), handler);
1019     _Unwind_SetIP(context, landingPad);
1020 
1021     return _URC_INSTALL_CONTEXT;
1022 }
1023