1 //===------------------------- cxa_exception.cpp --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //
9 //  This file implements the "Exception Handling APIs"
10 //  http://mentorembedded.github.io/cxx-abi/abi-eh.html
11 //  http://www.intel.com/design/itanium/downloads/245358.htm
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "config.h"
16 #include "unwind.h"
17 #include "cxa_exception.hpp"
18 #include "cxa_handlers.hpp"
19 #include "private_typeinfo.h"
20 #include <typeinfo>
21 #include <stdlib.h>
22 #include <assert.h>
23 
24 /*
25     Exception Header Layout:
26 
27 +---------------------------+-----------------------------+---------------+
28 | __cxa_exception           | _Unwind_Exception CLNGC++\0 | thrown object |
29 +---------------------------+-----------------------------+---------------+
30                                                           ^
31                                                           |
32   +-------------------------------------------------------+
33   |
34 +---------------------------+-----------------------------+
35 | __cxa_dependent_exception | _Unwind_Exception CLNGC++\1 |
36 +---------------------------+-----------------------------+
37 
38     Exception Handling Table Layout:
39 
40 +-----------------+--------+
41 | lpStartEncoding | (char) |
42 +---------+-------+--------+---------------+-----------------------+
43 | lpStart | (encoded with lpStartEncoding) | defaults to funcStart |
44 +---------+-----+--------+-----------------+---------------+-------+
45 | ttypeEncoding | (char) | Encoding of the type_info table |
46 +---------------+-+------+----+----------------------------+----------------+
47 | classInfoOffset | (ULEB128) | Offset to type_info table, defaults to null |
48 +-----------------++--------+-+----------------------------+----------------+
49 | callSiteEncoding | (char) | Encoding for Call Site Table |
50 +------------------+--+-----+-----+------------------------+--------------------------+
51 | callSiteTableLength | (ULEB128) | Call Site Table length, used to find Action table |
52 +---------------------+-----------+---------------------------------------------------+
53 #if !__USING_SJLJ_EXCEPTIONS__
54 +---------------------+-----------+------------------------------------------------+
55 | Beginning of Call Site Table            The current ip lies within the           |
56 | ...                                     (start, length) range of one of these    |
57 |                                         call sites. There may be action needed.  |
58 | +-------------+---------------------------------+------------------------------+ |
59 | | start       | (encoded with callSiteEncoding) | offset relative to funcStart | |
60 | | length      | (encoded with callSiteEncoding) | length of code fragment      | |
61 | | landingPad  | (encoded with callSiteEncoding) | offset relative to lpStart   | |
62 | | actionEntry | (ULEB128)                       | Action Table Index 1-based   | |
63 | |             |                                 | actionEntry == 0 -> cleanup  | |
64 | +-------------+---------------------------------+------------------------------+ |
65 | ...                                                                              |
66 +----------------------------------------------------------------------------------+
67 #else  // __USING_SJLJ_EXCEPTIONS__
68 +---------------------+-----------+------------------------------------------------+
69 | Beginning of Call Site Table            The current ip is a 1-based index into   |
70 | ...                                     this table.  Or it is -1 meaning no      |
71 |                                         action is needed.  Or it is 0 meaning    |
72 |                                         terminate.                               |
73 | +-------------+---------------------------------+------------------------------+ |
74 | | landingPad  | (ULEB128)                       | offset relative to lpStart   | |
75 | | actionEntry | (ULEB128)                       | Action Table Index 1-based   | |
76 | |             |                                 | actionEntry == 0 -> cleanup  | |
77 | +-------------+---------------------------------+------------------------------+ |
78 | ...                                                                              |
79 +----------------------------------------------------------------------------------+
80 #endif  // __USING_SJLJ_EXCEPTIONS__
81 +---------------------------------------------------------------------+
82 | Beginning of Action Table       ttypeIndex == 0 : cleanup           |
83 | ...                             ttypeIndex  > 0 : catch             |
84 |                                 ttypeIndex  < 0 : exception spec    |
85 | +--------------+-----------+--------------------------------------+ |
86 | | ttypeIndex   | (SLEB128) | Index into type_info Table (1-based) | |
87 | | actionOffset | (SLEB128) | Offset into next Action Table entry  | |
88 | +--------------+-----------+--------------------------------------+ |
89 | ...                                                                 |
90 +---------------------------------------------------------------------+-----------------+
91 | type_info Table, but classInfoOffset does *not* point here!                           |
92 | +----------------+------------------------------------------------+-----------------+ |
93 | | Nth type_info* | Encoded with ttypeEncoding, 0 means catch(...) | ttypeIndex == N | |
94 | +----------------+------------------------------------------------+-----------------+ |
95 | ...                                                                                   |
96 | +----------------+------------------------------------------------+-----------------+ |
97 | | 1st type_info* | Encoded with ttypeEncoding, 0 means catch(...) | ttypeIndex == 1 | |
98 | +----------------+------------------------------------------------+-----------------+ |
99 | +---------------------------------------+-----------+------------------------------+  |
100 | | 1st ttypeIndex for 1st exception spec | (ULEB128) | classInfoOffset points here! |  |
101 | | ...                                   | (ULEB128) |                              |  |
102 | | Mth ttypeIndex for 1st exception spec | (ULEB128) |                              |  |
103 | | 0                                     | (ULEB128) |                              |  |
104 | +---------------------------------------+------------------------------------------+  |
105 | ...                                                                                   |
106 | +---------------------------------------+------------------------------------------+  |
107 | | 0                                     | (ULEB128) | throw()                      |  |
108 | +---------------------------------------+------------------------------------------+  |
109 | ...                                                                                   |
110 | +---------------------------------------+------------------------------------------+  |
111 | | 1st ttypeIndex for Nth exception spec | (ULEB128) |                              |  |
112 | | ...                                   | (ULEB128) |                              |  |
113 | | Mth ttypeIndex for Nth exception spec | (ULEB128) |                              |  |
114 | | 0                                     | (ULEB128) |                              |  |
115 | +---------------------------------------+------------------------------------------+  |
116 +---------------------------------------------------------------------------------------+
117 
118 Notes:
119 
120 *  ttypeIndex in the Action Table, and in the exception spec table, is an index,
121      not a byte count, if positive.  It is a negative index offset of
122      classInfoOffset and the sizeof entry depends on ttypeEncoding.
123    But if ttypeIndex is negative, it is a positive 1-based byte offset into the
124      type_info Table.
125    And if ttypeIndex is zero, it refers to a catch (...).
126 
127 *  landingPad can be 0, this implies there is nothing to be done.
128 
129 *  landingPad != 0 and actionEntry == 0 implies a cleanup needs to be done
130      @landingPad.
131 
132 *  A cleanup can also be found under landingPad != 0 and actionEntry != 0 in
133      the Action Table with ttypeIndex == 0.
134 */
135 
136 namespace __cxxabiv1
137 {
138 
139 extern "C"
140 {
141 
142 // private API
143 
144 // Heavily borrowed from llvm/examples/ExceptionDemo/ExceptionDemo.cpp
145 
146 // DWARF Constants
147 enum
148 {
149     DW_EH_PE_absptr   = 0x00,
150     DW_EH_PE_uleb128  = 0x01,
151     DW_EH_PE_udata2   = 0x02,
152     DW_EH_PE_udata4   = 0x03,
153     DW_EH_PE_udata8   = 0x04,
154     DW_EH_PE_sleb128  = 0x09,
155     DW_EH_PE_sdata2   = 0x0A,
156     DW_EH_PE_sdata4   = 0x0B,
157     DW_EH_PE_sdata8   = 0x0C,
158     DW_EH_PE_pcrel    = 0x10,
159     DW_EH_PE_textrel  = 0x20,
160     DW_EH_PE_datarel  = 0x30,
161     DW_EH_PE_funcrel  = 0x40,
162     DW_EH_PE_aligned  = 0x50,
163     DW_EH_PE_indirect = 0x80,
164     DW_EH_PE_omit     = 0xFF
165 };
166 
167 /// Read a uleb128 encoded value and advance pointer
168 /// See Variable Length Data Appendix C in:
169 /// @link http://dwarfstd.org/Dwarf4.pdf @unlink
170 /// @param data reference variable holding memory pointer to decode from
171 /// @returns decoded value
172 static
173 uintptr_t
174 readULEB128(const uint8_t** data)
175 {
176     uintptr_t result = 0;
177     uintptr_t shift = 0;
178     unsigned char byte;
179     const uint8_t *p = *data;
180     do
181     {
182         byte = *p++;
183         result |= static_cast<uintptr_t>(byte & 0x7F) << shift;
184         shift += 7;
185     } while (byte & 0x80);
186     *data = p;
187     return result;
188 }
189 
190 /// Read a sleb128 encoded value and advance pointer
191 /// See Variable Length Data Appendix C in:
192 /// @link http://dwarfstd.org/Dwarf4.pdf @unlink
193 /// @param data reference variable holding memory pointer to decode from
194 /// @returns decoded value
195 static
196 intptr_t
197 readSLEB128(const uint8_t** data)
198 {
199     uintptr_t result = 0;
200     uintptr_t shift = 0;
201     unsigned char byte;
202     const uint8_t *p = *data;
203     do
204     {
205         byte = *p++;
206         result |= static_cast<uintptr_t>(byte & 0x7F) << shift;
207         shift += 7;
208     } while (byte & 0x80);
209     *data = p;
210     if ((byte & 0x40) && (shift < (sizeof(result) << 3)))
211         result |= static_cast<uintptr_t>(~0) << shift;
212     return static_cast<intptr_t>(result);
213 }
214 
215 /// Read a pointer encoded value and advance pointer
216 /// See Variable Length Data in:
217 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
218 /// @param data reference variable holding memory pointer to decode from
219 /// @param encoding dwarf encoding type
220 /// @returns decoded value
221 static
222 uintptr_t
223 readEncodedPointer(const uint8_t** data, uint8_t encoding)
224 {
225     uintptr_t result = 0;
226     if (encoding == DW_EH_PE_omit)
227         return result;
228     const uint8_t* p = *data;
229     // first get value
230     switch (encoding & 0x0F)
231     {
232     case DW_EH_PE_absptr:
233         result = *((uintptr_t*)p);
234         p += sizeof(uintptr_t);
235         break;
236     case DW_EH_PE_uleb128:
237         result = readULEB128(&p);
238         break;
239     case DW_EH_PE_sleb128:
240         result = static_cast<uintptr_t>(readSLEB128(&p));
241         break;
242     case DW_EH_PE_udata2:
243         result = *((uint16_t*)p);
244         p += sizeof(uint16_t);
245         break;
246     case DW_EH_PE_udata4:
247         result = *((uint32_t*)p);
248         p += sizeof(uint32_t);
249         break;
250     case DW_EH_PE_udata8:
251         result = static_cast<uintptr_t>(*((uint64_t*)p));
252         p += sizeof(uint64_t);
253         break;
254     case DW_EH_PE_sdata2:
255         result = static_cast<uintptr_t>(*((int16_t*)p));
256         p += sizeof(int16_t);
257         break;
258     case DW_EH_PE_sdata4:
259         result = static_cast<uintptr_t>(*((int32_t*)p));
260         p += sizeof(int32_t);
261         break;
262     case DW_EH_PE_sdata8:
263         result = static_cast<uintptr_t>(*((int64_t*)p));
264         p += sizeof(int64_t);
265         break;
266     default:
267         // not supported
268         abort();
269         break;
270     }
271     // then add relative offset
272     switch (encoding & 0x70)
273     {
274     case DW_EH_PE_absptr:
275         // do nothing
276         break;
277     case DW_EH_PE_pcrel:
278         if (result)
279             result += (uintptr_t)(*data);
280         break;
281     case DW_EH_PE_textrel:
282     case DW_EH_PE_datarel:
283     case DW_EH_PE_funcrel:
284     case DW_EH_PE_aligned:
285     default:
286         // not supported
287         abort();
288         break;
289     }
290     // then apply indirection
291     if (result && (encoding & DW_EH_PE_indirect))
292         result = *((uintptr_t*)result);
293     *data = p;
294     return result;
295 }
296 
297 static
298 void
299 call_terminate(bool native_exception, _Unwind_Exception* unwind_exception)
300 {
301     __cxa_begin_catch(unwind_exception);
302     if (native_exception)
303     {
304         // Use the stored terminate_handler if possible
305         __cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
306         std::__terminate(exception_header->terminateHandler);
307     }
308     std::terminate();
309 }
310 
311 #if LIBCXXABI_ARM_EHABI
312 static const void* read_target2_value(const void* ptr)
313 {
314     uintptr_t offset = *reinterpret_cast<const uintptr_t*>(ptr);
315     if (!offset)
316         return 0;
317     return *reinterpret_cast<const void **>(reinterpret_cast<uintptr_t>(ptr) +
318                                             offset);
319 }
320 
321 static const __shim_type_info*
322 get_shim_type_info(uint64_t ttypeIndex, const uint8_t* classInfo,
323                    uint8_t ttypeEncoding, bool native_exception,
324                    _Unwind_Exception* unwind_exception)
325 {
326     if (classInfo == 0)
327     {
328         // this should not happen.  Indicates corrupted eh_table.
329         call_terminate(native_exception, unwind_exception);
330     }
331 
332     assert(ttypeEncoding == DW_EH_PE_absptr && "Unexpected TTypeEncoding");
333     (void)ttypeEncoding;
334 
335     const uint8_t* ttypePtr = classInfo - ttypeIndex * sizeof(uintptr_t);
336     return reinterpret_cast<const __shim_type_info *>(
337         read_target2_value(ttypePtr));
338 }
339 #else // !LIBCXXABI_ARM_EHABI
340 static
341 const __shim_type_info*
342 get_shim_type_info(uint64_t ttypeIndex, const uint8_t* classInfo,
343                    uint8_t ttypeEncoding, bool native_exception,
344                    _Unwind_Exception* unwind_exception)
345 {
346     if (classInfo == 0)
347     {
348         // this should not happen.  Indicates corrupted eh_table.
349         call_terminate(native_exception, unwind_exception);
350     }
351     switch (ttypeEncoding & 0x0F)
352     {
353     case DW_EH_PE_absptr:
354         ttypeIndex *= sizeof(void*);
355         break;
356     case DW_EH_PE_udata2:
357     case DW_EH_PE_sdata2:
358         ttypeIndex *= 2;
359         break;
360     case DW_EH_PE_udata4:
361     case DW_EH_PE_sdata4:
362         ttypeIndex *= 4;
363         break;
364     case DW_EH_PE_udata8:
365     case DW_EH_PE_sdata8:
366         ttypeIndex *= 8;
367         break;
368     default:
369         // this should not happen.   Indicates corrupted eh_table.
370         call_terminate(native_exception, unwind_exception);
371     }
372     classInfo -= ttypeIndex;
373     return (const __shim_type_info*)readEncodedPointer(&classInfo, ttypeEncoding);
374 }
375 #endif // !LIBCXXABI_ARM_EHABI
376 
377 /*
378     This is checking a thrown exception type, excpType, against a possibly empty
379     list of catchType's which make up an exception spec.
380 
381     An exception spec acts like a catch handler, but in reverse.  This "catch
382     handler" will catch an excpType if and only if none of the catchType's in
383     the list will catch a excpType.  If any catchType in the list can catch an
384     excpType, then this exception spec does not catch the excpType.
385 */
386 #if LIBCXXABI_ARM_EHABI
387 static
388 bool
389 exception_spec_can_catch(int64_t specIndex, const uint8_t* classInfo,
390                          uint8_t ttypeEncoding, const __shim_type_info* excpType,
391                          void* adjustedPtr, _Unwind_Exception* unwind_exception)
392 {
393     if (classInfo == 0)
394     {
395         // this should not happen.   Indicates corrupted eh_table.
396         call_terminate(false, unwind_exception);
397     }
398 
399     assert(ttypeEncoding == DW_EH_PE_absptr && "Unexpected TTypeEncoding");
400     (void)ttypeEncoding;
401 
402     // specIndex is negative of 1-based byte offset into classInfo;
403     specIndex = -specIndex;
404     --specIndex;
405     const void** temp = reinterpret_cast<const void**>(
406         reinterpret_cast<uintptr_t>(classInfo) +
407         static_cast<uintptr_t>(specIndex) * sizeof(uintptr_t));
408     // If any type in the spec list can catch excpType, return false, else return true
409     //    adjustments to adjustedPtr are ignored.
410     while (true)
411     {
412         // ARM EHABI exception specification table (filter table) consists of
413         // several pointers which will directly point to the type info object
414         // (instead of ttypeIndex).  The table will be terminated with 0.
415         const void** ttypePtr = temp++;
416         if (*ttypePtr == 0)
417             break;
418         // We can get the __shim_type_info simply by performing a
419         // R_ARM_TARGET2 relocation, and cast the result to __shim_type_info.
420         const __shim_type_info* catchType =
421             static_cast<const __shim_type_info*>(read_target2_value(ttypePtr));
422         void* tempPtr = adjustedPtr;
423         if (catchType->can_catch(excpType, tempPtr))
424             return false;
425     }
426     return true;
427 }
428 #else
429 static
430 bool
431 exception_spec_can_catch(int64_t specIndex, const uint8_t* classInfo,
432                          uint8_t ttypeEncoding, const __shim_type_info* excpType,
433                          void* adjustedPtr, _Unwind_Exception* unwind_exception)
434 {
435     if (classInfo == 0)
436     {
437         // this should not happen.   Indicates corrupted eh_table.
438         call_terminate(false, unwind_exception);
439     }
440     // specIndex is negative of 1-based byte offset into classInfo;
441     specIndex = -specIndex;
442     --specIndex;
443     const uint8_t* temp = classInfo + specIndex;
444     // If any type in the spec list can catch excpType, return false, else return true
445     //    adjustments to adjustedPtr are ignored.
446     while (true)
447     {
448         uint64_t ttypeIndex = readULEB128(&temp);
449         if (ttypeIndex == 0)
450             break;
451         const __shim_type_info* catchType = get_shim_type_info(ttypeIndex,
452                                                                classInfo,
453                                                                ttypeEncoding,
454                                                                true,
455                                                                unwind_exception);
456         void* tempPtr = adjustedPtr;
457         if (catchType->can_catch(excpType, tempPtr))
458             return false;
459     }
460     return true;
461 }
462 #endif
463 
464 static
465 void*
466 get_thrown_object_ptr(_Unwind_Exception* unwind_exception)
467 {
468     // Even for foreign exceptions, the exception object is *probably* at unwind_exception + 1
469     //    Regardless, this library is prohibited from touching a foreign exception
470     void* adjustedPtr = unwind_exception + 1;
471     if (unwind_exception->exception_class == kOurDependentExceptionClass)
472         adjustedPtr = ((__cxa_dependent_exception*)adjustedPtr - 1)->primaryException;
473     return adjustedPtr;
474 }
475 
476 namespace
477 {
478 
479 struct scan_results
480 {
481     int64_t        ttypeIndex;   // > 0 catch handler, < 0 exception spec handler, == 0 a cleanup
482     const uint8_t* actionRecord;         // Currently unused.  Retained to ease future maintenance.
483     const uint8_t* languageSpecificData;  // Needed only for __cxa_call_unexpected
484     uintptr_t      landingPad;   // null -> nothing found, else something found
485     void*          adjustedPtr;  // Used in cxa_exception.cpp
486     _Unwind_Reason_Code reason;  // One of _URC_FATAL_PHASE1_ERROR,
487                                  //        _URC_FATAL_PHASE2_ERROR,
488                                  //        _URC_CONTINUE_UNWIND,
489                                  //        _URC_HANDLER_FOUND
490 };
491 
492 }  // unnamed namespace
493 
494 static
495 void
496 set_registers(_Unwind_Exception* unwind_exception, _Unwind_Context* context,
497               const scan_results& results)
498 {
499     _Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
500                                  reinterpret_cast<uintptr_t>(unwind_exception));
501     _Unwind_SetGR(context, __builtin_eh_return_data_regno(1),
502                                     static_cast<uintptr_t>(results.ttypeIndex));
503     _Unwind_SetIP(context, results.landingPad);
504 }
505 
506 /*
507     There are 3 types of scans needed:
508 
509     1.  Scan for handler with native or foreign exception.  If handler found,
510         save state and return _URC_HANDLER_FOUND, else return _URC_CONTINUE_UNWIND.
511         May also report an error on invalid input.
512         May terminate for invalid exception table.
513         _UA_SEARCH_PHASE
514 
515     2.  Scan for handler with foreign exception.  Must return _URC_HANDLER_FOUND,
516         or call terminate.
517         _UA_CLEANUP_PHASE && _UA_HANDLER_FRAME && !native_exception
518 
519     3.  Scan for cleanups.  If a handler is found and this isn't forced unwind,
520         then terminate, otherwise ignore the handler and keep looking for cleanup.
521         If a cleanup is found, return _URC_HANDLER_FOUND, else return _URC_CONTINUE_UNWIND.
522         May also report an error on invalid input.
523         May terminate for invalid exception table.
524         _UA_CLEANUP_PHASE && !_UA_HANDLER_FRAME
525 */
526 
527 static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
528                         bool native_exception,
529                         _Unwind_Exception *unwind_exception,
530                         _Unwind_Context *context) {
531     // Initialize results to found nothing but an error
532     results.ttypeIndex = 0;
533     results.actionRecord = 0;
534     results.languageSpecificData = 0;
535     results.landingPad = 0;
536     results.adjustedPtr = 0;
537     results.reason = _URC_FATAL_PHASE1_ERROR;
538     // Check for consistent actions
539     if (actions & _UA_SEARCH_PHASE)
540     {
541         // Do Phase 1
542         if (actions & (_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME | _UA_FORCE_UNWIND))
543         {
544             // None of these flags should be set during Phase 1
545             //   Client error
546             results.reason = _URC_FATAL_PHASE1_ERROR;
547             return;
548         }
549     }
550     else if (actions & _UA_CLEANUP_PHASE)
551     {
552         if ((actions & _UA_HANDLER_FRAME) && (actions & _UA_FORCE_UNWIND))
553         {
554             // _UA_HANDLER_FRAME should only be set if phase 1 found a handler.
555             // If _UA_FORCE_UNWIND is set, phase 1 shouldn't have happened.
556             //    Client error
557             results.reason = _URC_FATAL_PHASE2_ERROR;
558             return;
559         }
560     }
561     else // Neither _UA_SEARCH_PHASE nor _UA_CLEANUP_PHASE is set
562     {
563         // One of these should be set.
564         //   Client error
565         results.reason = _URC_FATAL_PHASE1_ERROR;
566         return;
567     }
568     // Start scan by getting exception table address
569     const uint8_t *lsda = (const uint8_t *)_Unwind_GetLanguageSpecificData(context);
570     if (lsda == 0)
571     {
572         // There is no exception table
573         results.reason = _URC_CONTINUE_UNWIND;
574         return;
575     }
576     results.languageSpecificData = lsda;
577     // Get the current instruction pointer and offset it before next
578     // instruction in the current frame which threw the exception.
579     uintptr_t ip = _Unwind_GetIP(context) - 1;
580     // Get beginning current frame's code (as defined by the
581     // emitted dwarf code)
582     uintptr_t funcStart = _Unwind_GetRegionStart(context);
583 #if __USING_SJLJ_EXCEPTIONS__
584     if (ip == uintptr_t(-1))
585     {
586         // no action
587         results.reason = _URC_CONTINUE_UNWIND;
588         return;
589     }
590     else if (ip == 0)
591         call_terminate(native_exception, unwind_exception);
592     // ip is 1-based index into call site table
593 #else  // !__USING_SJLJ_EXCEPTIONS__
594     uintptr_t ipOffset = ip - funcStart;
595 #endif  // !defined(_USING_SLJL_EXCEPTIONS__)
596     const uint8_t* classInfo = NULL;
597     // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
598     //       dwarf emission
599     // Parse LSDA header.
600     uint8_t lpStartEncoding = *lsda++;
601     const uint8_t* lpStart = (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding);
602     if (lpStart == 0)
603         lpStart = (const uint8_t*)funcStart;
604     uint8_t ttypeEncoding = *lsda++;
605     if (ttypeEncoding != DW_EH_PE_omit)
606     {
607         // Calculate type info locations in emitted dwarf code which
608         // were flagged by type info arguments to llvm.eh.selector
609         // intrinsic
610         uintptr_t classInfoOffset = readULEB128(&lsda);
611         classInfo = lsda + classInfoOffset;
612     }
613     // Walk call-site table looking for range that
614     // includes current PC.
615     uint8_t callSiteEncoding = *lsda++;
616 #if __USING_SJLJ_EXCEPTIONS__
617     (void)callSiteEncoding;  // When using SjLj exceptions, callSiteEncoding is never used
618 #endif
619     uint32_t callSiteTableLength = static_cast<uint32_t>(readULEB128(&lsda));
620     const uint8_t* callSiteTableStart = lsda;
621     const uint8_t* callSiteTableEnd = callSiteTableStart + callSiteTableLength;
622     const uint8_t* actionTableStart = callSiteTableEnd;
623     const uint8_t* callSitePtr = callSiteTableStart;
624     while (callSitePtr < callSiteTableEnd)
625     {
626         // There is one entry per call site.
627 #if !__USING_SJLJ_EXCEPTIONS__
628         // The call sites are non-overlapping in [start, start+length)
629         // The call sites are ordered in increasing value of start
630         uintptr_t start = readEncodedPointer(&callSitePtr, callSiteEncoding);
631         uintptr_t length = readEncodedPointer(&callSitePtr, callSiteEncoding);
632         uintptr_t landingPad = readEncodedPointer(&callSitePtr, callSiteEncoding);
633         uintptr_t actionEntry = readULEB128(&callSitePtr);
634         if ((start <= ipOffset) && (ipOffset < (start + length)))
635 #else  // __USING_SJLJ_EXCEPTIONS__
636         // ip is 1-based index into this table
637         uintptr_t landingPad = readULEB128(&callSitePtr);
638         uintptr_t actionEntry = readULEB128(&callSitePtr);
639         if (--ip == 0)
640 #endif  // __USING_SJLJ_EXCEPTIONS__
641         {
642             // Found the call site containing ip.
643 #if !__USING_SJLJ_EXCEPTIONS__
644             if (landingPad == 0)
645             {
646                 // No handler here
647                 results.reason = _URC_CONTINUE_UNWIND;
648                 return;
649             }
650             landingPad = (uintptr_t)lpStart + landingPad;
651 #else  // __USING_SJLJ_EXCEPTIONS__
652             ++landingPad;
653 #endif  // __USING_SJLJ_EXCEPTIONS__
654             if (actionEntry == 0)
655             {
656                 // Found a cleanup
657                 // If this is a type 1 or type 2 search, there are no handlers
658                 // If this is a type 3 search, you want to install the cleanup.
659                 if ((actions & _UA_CLEANUP_PHASE) && !(actions & _UA_HANDLER_FRAME))
660                 {
661                     results.ttypeIndex = 0;  // Redundant but clarifying
662                     results.landingPad = landingPad;
663                     results.reason = _URC_HANDLER_FOUND;
664                     return;
665                 }
666                 // No handler here
667                 results.reason = _URC_CONTINUE_UNWIND;
668                 return;
669             }
670             // Convert 1-based byte offset into
671             const uint8_t* action = actionTableStart + (actionEntry - 1);
672             // Scan action entries until you find a matching handler, cleanup, or the end of action list
673             while (true)
674             {
675                 const uint8_t* actionRecord = action;
676                 int64_t ttypeIndex = readSLEB128(&action);
677                 if (ttypeIndex > 0)
678                 {
679                     // Found a catch, does it actually catch?
680                     // First check for catch (...)
681                     const __shim_type_info* catchType =
682                         get_shim_type_info(static_cast<uint64_t>(ttypeIndex),
683                                            classInfo, ttypeEncoding,
684                                            native_exception, unwind_exception);
685                     if (catchType == 0)
686                     {
687                         // Found catch (...) catches everything, including foreign exceptions
688                         // If this is a type 1 search save state and return _URC_HANDLER_FOUND
689                         // If this is a type 2 search save state and return _URC_HANDLER_FOUND
690                         // If this is a type 3 search !_UA_FORCE_UNWIND, we should have found this in phase 1!
691                         // If this is a type 3 search _UA_FORCE_UNWIND, ignore handler and continue scan
692                         if ((actions & _UA_SEARCH_PHASE) || (actions & _UA_HANDLER_FRAME))
693                         {
694                             // Save state and return _URC_HANDLER_FOUND
695                             results.ttypeIndex = ttypeIndex;
696                             results.actionRecord = actionRecord;
697                             results.landingPad = landingPad;
698                             results.adjustedPtr = get_thrown_object_ptr(unwind_exception);
699                             results.reason = _URC_HANDLER_FOUND;
700                             return;
701                         }
702                         else if (!(actions & _UA_FORCE_UNWIND))
703                         {
704                             // It looks like the exception table has changed
705                             //    on us.  Likely stack corruption!
706                             call_terminate(native_exception, unwind_exception);
707                         }
708                     }
709                     // Else this is a catch (T) clause and will never
710                     //    catch a foreign exception
711                     else if (native_exception)
712                     {
713                         __cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
714                         void* adjustedPtr = get_thrown_object_ptr(unwind_exception);
715                         const __shim_type_info* excpType =
716                             static_cast<const __shim_type_info*>(exception_header->exceptionType);
717                         if (adjustedPtr == 0 || excpType == 0)
718                         {
719                             // Something very bad happened
720                             call_terminate(native_exception, unwind_exception);
721                         }
722                         if (catchType->can_catch(excpType, adjustedPtr))
723                         {
724                             // Found a matching handler
725                             // If this is a type 1 search save state and return _URC_HANDLER_FOUND
726                             // If this is a type 3 search and !_UA_FORCE_UNWIND, we should have found this in phase 1!
727                             // If this is a type 3 search and _UA_FORCE_UNWIND, ignore handler and continue scan
728                             if (actions & _UA_SEARCH_PHASE)
729                             {
730                                 // Save state and return _URC_HANDLER_FOUND
731                                 results.ttypeIndex = ttypeIndex;
732                                 results.actionRecord = actionRecord;
733                                 results.landingPad = landingPad;
734                                 results.adjustedPtr = adjustedPtr;
735                                 results.reason = _URC_HANDLER_FOUND;
736                                 return;
737                             }
738                             else if (!(actions & _UA_FORCE_UNWIND))
739                             {
740                                 // It looks like the exception table has changed
741                                 //    on us.  Likely stack corruption!
742                                 call_terminate(native_exception, unwind_exception);
743                             }
744                         }
745                     }
746                     // Scan next action ...
747                 }
748                 else if (ttypeIndex < 0)
749                 {
750                     // Found an exception spec.  If this is a foreign exception,
751                     //   it is always caught.
752                     if (native_exception)
753                     {
754                         // Does the exception spec catch this native exception?
755                         __cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
756                         void* adjustedPtr = get_thrown_object_ptr(unwind_exception);
757                         const __shim_type_info* excpType =
758                             static_cast<const __shim_type_info*>(exception_header->exceptionType);
759                         if (adjustedPtr == 0 || excpType == 0)
760                         {
761                             // Something very bad happened
762                             call_terminate(native_exception, unwind_exception);
763                         }
764                         if (exception_spec_can_catch(ttypeIndex, classInfo,
765                                                      ttypeEncoding, excpType,
766                                                      adjustedPtr, unwind_exception))
767                         {
768                             // native exception caught by exception spec
769                             // If this is a type 1 search, save state and return _URC_HANDLER_FOUND
770                             // If this is a type 3 search !_UA_FORCE_UNWIND, we should have found this in phase 1!
771                             // If this is a type 3 search _UA_FORCE_UNWIND, ignore handler and continue scan
772                             if (actions & _UA_SEARCH_PHASE)
773                             {
774                                 // Save state and return _URC_HANDLER_FOUND
775                                 results.ttypeIndex = ttypeIndex;
776                                 results.actionRecord = actionRecord;
777                                 results.landingPad = landingPad;
778                                 results.adjustedPtr = adjustedPtr;
779                                 results.reason = _URC_HANDLER_FOUND;
780                                 return;
781                             }
782                             else if (!(actions & _UA_FORCE_UNWIND))
783                             {
784                                 // It looks like the exception table has changed
785                                 //    on us.  Likely stack corruption!
786                                 call_terminate(native_exception, unwind_exception);
787                             }
788                         }
789                     }
790                     else
791                     {
792                         // foreign exception caught by exception spec
793                         // If this is a type 1 search, save state and return _URC_HANDLER_FOUND
794                         // If this is a type 2 search, save state and return _URC_HANDLER_FOUND
795                         // If this is a type 3 search !_UA_FORCE_UNWIND, we should have found this in phase 1!
796                         // If this is a type 3 search _UA_FORCE_UNWIND, ignore handler and continue scan
797                         if ((actions & _UA_SEARCH_PHASE) || (actions & _UA_HANDLER_FRAME))
798                         {
799                             // Save state and return _URC_HANDLER_FOUND
800                             results.ttypeIndex = ttypeIndex;
801                             results.actionRecord = actionRecord;
802                             results.landingPad = landingPad;
803                             results.adjustedPtr = get_thrown_object_ptr(unwind_exception);
804                             results.reason = _URC_HANDLER_FOUND;
805                             return;
806                         }
807                         else if (!(actions & _UA_FORCE_UNWIND))
808                         {
809                             // It looks like the exception table has changed
810                             //    on us.  Likely stack corruption!
811                             call_terminate(native_exception, unwind_exception);
812                         }
813                     }
814                     // Scan next action ...
815                 }
816                 else  // ttypeIndex == 0
817                 {
818                     // Found a cleanup
819                     // If this is a type 1 search, ignore it and continue scan
820                     // If this is a type 2 search, ignore it and continue scan
821                     // If this is a type 3 search, save state and return _URC_HANDLER_FOUND
822                     if ((actions & _UA_CLEANUP_PHASE) && !(actions & _UA_HANDLER_FRAME))
823                     {
824                         // Save state and return _URC_HANDLER_FOUND
825                         results.ttypeIndex = ttypeIndex;
826                         results.actionRecord = actionRecord;
827                         results.landingPad = landingPad;
828                         results.adjustedPtr = get_thrown_object_ptr(unwind_exception);
829                         results.reason = _URC_HANDLER_FOUND;
830                         return;
831                     }
832                 }
833                 const uint8_t* temp = action;
834                 int64_t actionOffset = readSLEB128(&temp);
835                 if (actionOffset == 0)
836                 {
837                     // End of action list, no matching handler or cleanup found
838                     results.reason = _URC_CONTINUE_UNWIND;
839                     return;
840                 }
841                 // Go to next action
842                 action += actionOffset;
843             }  // there is no break out of this loop, only return
844         }
845 #if !__USING_SJLJ_EXCEPTIONS__
846         else if (ipOffset < start)
847         {
848             // There is no call site for this ip
849             // Something bad has happened.  We should never get here.
850             // Possible stack corruption.
851             call_terminate(native_exception, unwind_exception);
852         }
853 #endif  // !__USING_SJLJ_EXCEPTIONS__
854     }  // there might be some tricky cases which break out of this loop
855 
856     // It is possible that no eh table entry specify how to handle
857     // this exception. By spec, terminate it immediately.
858     call_terminate(native_exception, unwind_exception);
859 }
860 
861 // public API
862 
863 /*
864 The personality function branches on actions like so:
865 
866 _UA_SEARCH_PHASE
867 
868     If _UA_CLEANUP_PHASE or _UA_HANDLER_FRAME or _UA_FORCE_UNWIND there's
869       an error from above, return _URC_FATAL_PHASE1_ERROR.
870 
871     Scan for anything that could stop unwinding:
872 
873        1.  A catch clause that will catch this exception
874            (will never catch foreign).
875        2.  A catch (...) (will always catch foreign).
876        3.  An exception spec that will catch this exception
877            (will always catch foreign).
878     If a handler is found
879         If not foreign
880             Save state in header
881         return _URC_HANDLER_FOUND
882     Else a handler not found
883         return _URC_CONTINUE_UNWIND
884 
885 _UA_CLEANUP_PHASE
886 
887     If _UA_HANDLER_FRAME
888         If _UA_FORCE_UNWIND
889             How did this happen?  return _URC_FATAL_PHASE2_ERROR
890         If foreign
891             Do _UA_SEARCH_PHASE to recover state
892         else
893             Recover state from header
894         Transfer control to landing pad.  return _URC_INSTALL_CONTEXT
895 
896     Else
897 
898         This branch handles both normal C++ non-catching handlers (cleanups)
899           and forced unwinding.
900         Scan for anything that can not stop unwinding:
901 
902             1.  A cleanup.
903 
904         If a cleanup is found
905             transfer control to it. return _URC_INSTALL_CONTEXT
906         Else a cleanup is not found: return _URC_CONTINUE_UNWIND
907 */
908 
909 #if !LIBCXXABI_ARM_EHABI
910 _Unwind_Reason_Code
911 #if __USING_SJLJ_EXCEPTIONS__
912 __gxx_personality_sj0
913 #else
914 __gxx_personality_v0
915 #endif
916                     (int version, _Unwind_Action actions, uint64_t exceptionClass,
917                      _Unwind_Exception* unwind_exception, _Unwind_Context* context)
918 {
919     if (version != 1 || unwind_exception == 0 || context == 0)
920         return _URC_FATAL_PHASE1_ERROR;
921 
922     bool native_exception = (exceptionClass     & get_vendor_and_language) ==
923                             (kOurExceptionClass & get_vendor_and_language);
924     scan_results results;
925     if (actions & _UA_SEARCH_PHASE)
926     {
927         // Phase 1 search:  All we're looking for in phase 1 is a handler that
928         //   halts unwinding
929         scan_eh_tab(results, actions, native_exception, unwind_exception, context);
930         if (results.reason == _URC_HANDLER_FOUND)
931         {
932             // Found one.  Can we cache the results somewhere to optimize phase 2?
933             if (native_exception)
934             {
935                 __cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
936                 exception_header->handlerSwitchValue = static_cast<int>(results.ttypeIndex);
937                 exception_header->actionRecord = results.actionRecord;
938                 exception_header->languageSpecificData = results.languageSpecificData;
939                 exception_header->catchTemp = reinterpret_cast<void*>(results.landingPad);
940                 exception_header->adjustedPtr = results.adjustedPtr;
941             }
942             return _URC_HANDLER_FOUND;
943         }
944         // Did not find a catching-handler.  Return the results of the scan
945         //    (normally _URC_CONTINUE_UNWIND, but could have been _URC_FATAL_PHASE1_ERROR
946         //     if we were called improperly).
947         return results.reason;
948     }
949     if (actions & _UA_CLEANUP_PHASE)
950     {
951         // Phase 2 search:
952         //  Did we find a catching handler in phase 1?
953         if (actions & _UA_HANDLER_FRAME)
954         {
955             // Yes, phase 1 said we have a catching handler here.
956             // Did we cache the results of the scan?
957             if (native_exception)
958             {
959                 // Yes, reload the results from the cache.
960                 __cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
961                 results.ttypeIndex = exception_header->handlerSwitchValue;
962                 results.actionRecord = exception_header->actionRecord;
963                 results.languageSpecificData = exception_header->languageSpecificData;
964                 results.landingPad = reinterpret_cast<uintptr_t>(exception_header->catchTemp);
965                 results.adjustedPtr = exception_header->adjustedPtr;
966             }
967             else
968             {
969                 // No, do the scan again to reload the results.
970                 scan_eh_tab(results, actions, native_exception, unwind_exception, context);
971                 // Phase 1 told us we would find a handler.  Now in Phase 2 we
972                 //   didn't find a handler.  The eh table should not be changing!
973                 if (results.reason != _URC_HANDLER_FOUND)
974                     call_terminate(native_exception, unwind_exception);
975             }
976             // Jump to the handler
977             set_registers(unwind_exception, context, results);
978             return _URC_INSTALL_CONTEXT;
979         }
980         // Either we didn't do a phase 1 search (due to forced unwinding), or
981         //   phase 1 reported no catching-handlers.
982         // Search for a (non-catching) cleanup
983         scan_eh_tab(results, actions, native_exception, unwind_exception, context);
984         if (results.reason == _URC_HANDLER_FOUND)
985         {
986             // Found a non-catching handler.  Jump to it:
987             set_registers(unwind_exception, context, results);
988             return _URC_INSTALL_CONTEXT;
989         }
990         // Did not find a cleanup.  Return the results of the scan
991         //    (normally _URC_CONTINUE_UNWIND, but could have been _URC_FATAL_PHASE2_ERROR
992         //     if we were called improperly).
993         return results.reason;
994     }
995     // We were called improperly: neither a phase 1 or phase 2 search
996     return _URC_FATAL_PHASE1_ERROR;
997 }
998 #else
999 
1000 // Helper function to unwind one frame.
1001 // ARM EHABI 7.3 and 7.4: If the personality function returns _URC_CONTINUE_UNWIND, the
1002 // personality routine should update the virtual register set (VRS) according to the
1003 // corresponding frame unwinding instructions (ARM EHABI 9.3.)
1004 static _Unwind_Reason_Code continue_unwind(_Unwind_Context* context,
1005                                            uint32_t* unwind_opcodes,
1006                                            size_t opcode_words)
1007 {
1008     if (_Unwind_VRS_Interpret(context, unwind_opcodes, 1, opcode_words * 4) !=
1009         _URC_CONTINUE_UNWIND)
1010         return _URC_FAILURE;
1011     return _URC_CONTINUE_UNWIND;
1012 }
1013 
1014 // ARM register names
1015 static const uint32_t REG_UCB = 12;  // Register to save _Unwind_Control_Block
1016 static const uint32_t REG_SP = 13;
1017 
1018 static void save_results_to_barrier_cache(_Unwind_Exception* unwind_exception,
1019                                           const scan_results& results)
1020 {
1021     unwind_exception->barrier_cache.bitpattern[0] = (uint32_t)results.adjustedPtr;
1022     unwind_exception->barrier_cache.bitpattern[1] = (uint32_t)results.actionRecord;
1023     unwind_exception->barrier_cache.bitpattern[2] = (uint32_t)results.languageSpecificData;
1024     unwind_exception->barrier_cache.bitpattern[3] = (uint32_t)results.landingPad;
1025     unwind_exception->barrier_cache.bitpattern[4] = (uint32_t)results.ttypeIndex;
1026 }
1027 
1028 static void load_results_from_barrier_cache(scan_results& results,
1029                                             const _Unwind_Exception* unwind_exception)
1030 {
1031     results.adjustedPtr = (void*)unwind_exception->barrier_cache.bitpattern[0];
1032     results.actionRecord = (const uint8_t*)unwind_exception->barrier_cache.bitpattern[1];
1033     results.languageSpecificData = (const uint8_t*)unwind_exception->barrier_cache.bitpattern[2];
1034     results.landingPad = (uintptr_t)unwind_exception->barrier_cache.bitpattern[3];
1035     results.ttypeIndex = (int64_t)(int32_t)unwind_exception->barrier_cache.bitpattern[4];
1036 }
1037 
1038 extern "C" _Unwind_Reason_Code
1039 __gxx_personality_v0(_Unwind_State state,
1040                      _Unwind_Exception* unwind_exception,
1041                      _Unwind_Context* context)
1042 {
1043     if (unwind_exception == 0 || context == 0)
1044         return _URC_FATAL_PHASE1_ERROR;
1045 
1046     bool native_exception = (unwind_exception->exception_class & get_vendor_and_language) ==
1047                             (kOurExceptionClass & get_vendor_and_language);
1048 
1049 #if LIBCXXABI_ARM_EHABI
1050     // ARM EHABI # 6.2, # 9.2
1051     //
1052     //  +---- ehtp
1053     //  v
1054     // +--------------------------------------+
1055     // | +--------+--------+--------+-------+ |
1056     // | |0| prel31 to __gxx_personality_v0 | |
1057     // | +--------+--------+--------+-------+ |
1058     // | |      N |      unwind opcodes     | |  <-- UnwindData
1059     // | +--------+--------+--------+-------+ |
1060     // | | Word 2        unwind opcodes     | |
1061     // | +--------+--------+--------+-------+ |
1062     // | ...                                  |
1063     // | +--------+--------+--------+-------+ |
1064     // | | Word N        unwind opcodes     | |
1065     // | +--------+--------+--------+-------+ |
1066     // | | LSDA                             | |  <-- lsda
1067     // | | ...                              | |
1068     // | +--------+--------+--------+-------+ |
1069     // +--------------------------------------+
1070 
1071     uint32_t *UnwindData = unwind_exception->pr_cache.ehtp + 1;
1072     uint32_t FirstDataWord = *UnwindData;
1073     size_t N = ((FirstDataWord >> 24) & 0xff);
1074     size_t NDataWords = N + 1;
1075 #endif
1076 
1077     // Copy the address of _Unwind_Control_Block to r12 so that
1078     // _Unwind_GetLanguageSpecificData() and _Unwind_GetRegionStart() can
1079     // return correct address.
1080     _Unwind_SetGR(context, REG_UCB, reinterpret_cast<uint32_t>(unwind_exception));
1081 
1082     scan_results results;
1083     switch (state) {
1084     case _US_VIRTUAL_UNWIND_FRAME:
1085         // Phase 1 search:  All we're looking for in phase 1 is a handler that halts unwinding
1086         scan_eh_tab(results, _UA_SEARCH_PHASE, native_exception, unwind_exception, context);
1087         if (results.reason == _URC_HANDLER_FOUND)
1088         {
1089             unwind_exception->barrier_cache.sp = _Unwind_GetGR(context, REG_SP);
1090             if (native_exception)
1091                 save_results_to_barrier_cache(unwind_exception, results);
1092             return _URC_HANDLER_FOUND;
1093         }
1094         // Did not find the catch handler
1095         if (results.reason == _URC_CONTINUE_UNWIND)
1096             return continue_unwind(context, UnwindData, NDataWords);
1097         return results.reason;
1098 
1099     case _US_UNWIND_FRAME_STARTING:
1100         // Phase 2 search
1101         if (unwind_exception->barrier_cache.sp == _Unwind_GetGR(context, REG_SP))
1102         {
1103             // Found a catching handler in phase 1
1104             if (native_exception)
1105             {
1106                 // Load the result from the native exception barrier cache.
1107                 load_results_from_barrier_cache(results, unwind_exception);
1108                 results.reason = _URC_HANDLER_FOUND;
1109             }
1110             else
1111             {
1112                 // Search for the catching handler again for the foreign exception.
1113                 scan_eh_tab(results, static_cast<_Unwind_Action>(_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME),
1114                             native_exception, unwind_exception, context);
1115                 if (results.reason != _URC_HANDLER_FOUND)  // phase1 search should guarantee to find one
1116                     call_terminate(native_exception, unwind_exception);
1117             }
1118 
1119             // Install the context for the catching handler
1120             set_registers(unwind_exception, context, results);
1121             return _URC_INSTALL_CONTEXT;
1122         }
1123 
1124         // Either we didn't do a phase 1 search (due to forced unwinding), or
1125         //  phase 1 reported no catching-handlers.
1126         // Search for a (non-catching) cleanup
1127         scan_eh_tab(results, _UA_CLEANUP_PHASE, native_exception, unwind_exception, context);
1128         if (results.reason == _URC_HANDLER_FOUND)
1129         {
1130             // Found a non-catching handler
1131 
1132             // ARM EHABI 8.4.2: Before we can jump to the cleanup handler, we have to setup some
1133             // internal data structures, so that __cxa_end_cleanup() can get unwind_exception from
1134             // __cxa_get_globals().
1135             __cxa_begin_cleanup(unwind_exception);
1136 
1137             // Install the context for the cleanup handler
1138             set_registers(unwind_exception, context, results);
1139             return _URC_INSTALL_CONTEXT;
1140         }
1141 
1142         // Did not find any handler
1143         if (results.reason == _URC_CONTINUE_UNWIND)
1144             return continue_unwind(context, UnwindData, NDataWords);
1145         return results.reason;
1146 
1147     case _US_UNWIND_FRAME_RESUME:
1148         return continue_unwind(context, UnwindData, NDataWords);
1149     }
1150 
1151     // We were called improperly: neither a phase 1 or phase 2 search
1152     return _URC_FATAL_PHASE1_ERROR;
1153 }
1154 #endif
1155 
1156 
1157 __attribute__((noreturn))
1158 void
1159 __cxa_call_unexpected(void* arg)
1160 {
1161     _Unwind_Exception* unwind_exception = static_cast<_Unwind_Exception*>(arg);
1162     if (unwind_exception == 0)
1163         call_terminate(false, unwind_exception);
1164     __cxa_begin_catch(unwind_exception);
1165     bool native_old_exception =
1166         (unwind_exception->exception_class & get_vendor_and_language) ==
1167         (kOurExceptionClass                & get_vendor_and_language);
1168     std::unexpected_handler u_handler;
1169     std::terminate_handler t_handler;
1170     __cxa_exception* old_exception_header = 0;
1171     int64_t ttypeIndex;
1172     const uint8_t* lsda;
1173     if (native_old_exception)
1174     {
1175         old_exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
1176         t_handler = old_exception_header->terminateHandler;
1177         u_handler = old_exception_header->unexpectedHandler;
1178         // If std::__unexpected(u_handler) rethrows the same exception,
1179         //   these values get overwritten by the rethrow.  So save them now:
1180 #if LIBCXXABI_ARM_EHABI
1181         ttypeIndex = (int64_t)(int32_t)unwind_exception->barrier_cache.bitpattern[4];
1182         lsda = (const uint8_t*)unwind_exception->barrier_cache.bitpattern[2];
1183 #else
1184         ttypeIndex = old_exception_header->handlerSwitchValue;
1185         lsda = old_exception_header->languageSpecificData;
1186 #endif
1187     }
1188     else
1189     {
1190         t_handler = std::get_terminate();
1191         u_handler = std::get_unexpected();
1192     }
1193     try
1194     {
1195         std::__unexpected(u_handler);
1196     }
1197     catch (...)
1198     {
1199         // If the old exception is foreign, then all we can do is terminate.
1200         //   We have no way to recover the needed old exception spec.  There's
1201         //   no way to pass that information here.  And the personality routine
1202         //   can't call us directly and do anything but terminate() if we throw
1203         //   from here.
1204         if (native_old_exception)
1205         {
1206             // Have:
1207             //   old_exception_header->languageSpecificData
1208             //   old_exception_header->actionRecord
1209             // Need
1210             //   const uint8_t* classInfo
1211             //   uint8_t ttypeEncoding
1212             uint8_t lpStartEncoding = *lsda++;
1213             const uint8_t* lpStart = (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding);
1214             (void)lpStart;  // purposefully unused.  Just needed to increment lsda.
1215             uint8_t ttypeEncoding = *lsda++;
1216             if (ttypeEncoding == DW_EH_PE_omit)
1217                 std::__terminate(t_handler);
1218             uintptr_t classInfoOffset = readULEB128(&lsda);
1219             const uint8_t* classInfo = lsda + classInfoOffset;
1220             // Is this new exception catchable by the exception spec at ttypeIndex?
1221             // The answer is obviously yes if the new and old exceptions are the same exception
1222             // If no
1223             //    throw;
1224             __cxa_eh_globals* globals = __cxa_get_globals_fast();
1225             __cxa_exception* new_exception_header = globals->caughtExceptions;
1226             if (new_exception_header == 0)
1227                 // This shouldn't be able to happen!
1228                 std::__terminate(t_handler);
1229             bool native_new_exception =
1230                 (new_exception_header->unwindHeader.exception_class & get_vendor_and_language) ==
1231                                                 (kOurExceptionClass & get_vendor_and_language);
1232             void* adjustedPtr;
1233             if (native_new_exception && (new_exception_header != old_exception_header))
1234             {
1235                 const __shim_type_info* excpType =
1236                     static_cast<const __shim_type_info*>(new_exception_header->exceptionType);
1237                 adjustedPtr =
1238                     new_exception_header->unwindHeader.exception_class == kOurDependentExceptionClass ?
1239                         ((__cxa_dependent_exception*)new_exception_header)->primaryException :
1240                         new_exception_header + 1;
1241                 if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
1242                                               excpType, adjustedPtr, unwind_exception))
1243                 {
1244                     // We need to __cxa_end_catch, but for the old exception,
1245                     //   not the new one.  This is a little tricky ...
1246                     // Disguise new_exception_header as a rethrown exception, but
1247                     //   don't actually rethrow it.  This means you can temporarily
1248                     //   end the catch clause enclosing new_exception_header without
1249                     //   __cxa_end_catch destroying new_exception_header.
1250                     new_exception_header->handlerCount = -new_exception_header->handlerCount;
1251                     globals->uncaughtExceptions += 1;
1252                     // Call __cxa_end_catch for new_exception_header
1253                     __cxa_end_catch();
1254                     // Call __cxa_end_catch for old_exception_header
1255                     __cxa_end_catch();
1256                     // Renter this catch clause with new_exception_header
1257                     __cxa_begin_catch(&new_exception_header->unwindHeader);
1258                     // Rethrow new_exception_header
1259                     throw;
1260                 }
1261             }
1262             // Will a std::bad_exception be catchable by the exception spec at
1263             //   ttypeIndex?
1264             // If no
1265             //    throw std::bad_exception();
1266             const __shim_type_info* excpType =
1267                 static_cast<const __shim_type_info*>(&typeid(std::bad_exception));
1268             std::bad_exception be;
1269             adjustedPtr = &be;
1270             if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
1271                                           excpType, adjustedPtr, unwind_exception))
1272             {
1273                 // We need to __cxa_end_catch for both the old exception and the
1274                 //   new exception.  Technically we should do it in that order.
1275                 //   But it is expedient to do it in the opposite order:
1276                 // Call __cxa_end_catch for new_exception_header
1277                 __cxa_end_catch();
1278                 // Throw std::bad_exception will __cxa_end_catch for
1279                 //   old_exception_header
1280                 throw be;
1281             }
1282         }
1283     }
1284     std::__terminate(t_handler);
1285 }
1286 
1287 }  // extern "C"
1288 
1289 }  // __cxxabiv1
1290