1 //===--------------------------- Unwind-EHABI.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 //  Implements ARM zero-cost C++ exceptions
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "Unwind-EHABI.h"
14 
15 #if _LIBUNWIND_ARM_EHABI
16 
17 #include <stdbool.h>
18 #include <stdint.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 
23 #include <type_traits>
24 
25 #include "config.h"
26 #include "libunwind.h"
27 #include "libunwind_ext.h"
28 #include "unwind.h"
29 
30 namespace {
31 
32 // Strange order: take words in order, but inside word, take from most to least
33 // signinficant byte.
34 uint8_t getByte(const uint32_t* data, size_t offset) {
35   const uint8_t* byteData = reinterpret_cast<const uint8_t*>(data);
36   return byteData[(offset & ~(size_t)0x03) + (3 - (offset & (size_t)0x03))];
37 }
38 
39 const char* getNextWord(const char* data, uint32_t* out) {
40   *out = *reinterpret_cast<const uint32_t*>(data);
41   return data + 4;
42 }
43 
44 const char* getNextNibble(const char* data, uint32_t* out) {
45   *out = *reinterpret_cast<const uint16_t*>(data);
46   return data + 2;
47 }
48 
49 struct Descriptor {
50   // See # 9.2
51   typedef enum {
52     SU16 = 0, // Short descriptor, 16-bit entries
53     LU16 = 1, // Long descriptor,  16-bit entries
54     LU32 = 3, // Long descriptor,  32-bit entries
55     RESERVED0 =  4, RESERVED1 =  5, RESERVED2  = 6,  RESERVED3  =  7,
56     RESERVED4 =  8, RESERVED5 =  9, RESERVED6  = 10, RESERVED7  = 11,
57     RESERVED8 = 12, RESERVED9 = 13, RESERVED10 = 14, RESERVED11 = 15
58   } Format;
59 
60   // See # 9.2
61   typedef enum {
62     CLEANUP = 0x0,
63     FUNC    = 0x1,
64     CATCH   = 0x2,
65     INVALID = 0x4
66   } Kind;
67 };
68 
69 _Unwind_Reason_Code ProcessDescriptors(
70     _Unwind_State state,
71     _Unwind_Control_Block* ucbp,
72     struct _Unwind_Context* context,
73     Descriptor::Format format,
74     const char* descriptorStart,
75     uint32_t flags) {
76 
77   // EHT is inlined in the index using compact form. No descriptors. #5
78   if (flags & 0x1)
79     return _URC_CONTINUE_UNWIND;
80 
81   // TODO: We should check the state here, and determine whether we need to
82   // perform phase1 or phase2 unwinding.
83   (void)state;
84 
85   const char* descriptor = descriptorStart;
86   uint32_t descriptorWord;
87   getNextWord(descriptor, &descriptorWord);
88   while (descriptorWord) {
89     // Read descriptor based on # 9.2.
90     uint32_t length;
91     uint32_t offset;
92     switch (format) {
93       case Descriptor::LU32:
94         descriptor = getNextWord(descriptor, &length);
95         descriptor = getNextWord(descriptor, &offset);
96       case Descriptor::LU16:
97         descriptor = getNextNibble(descriptor, &length);
98         descriptor = getNextNibble(descriptor, &offset);
99       default:
100         assert(false);
101         return _URC_FAILURE;
102     }
103 
104     // See # 9.2 table for decoding the kind of descriptor. It's a 2-bit value.
105     Descriptor::Kind kind =
106         static_cast<Descriptor::Kind>((length & 0x1) | ((offset & 0x1) << 1));
107 
108     // Clear off flag from last bit.
109     length &= ~1u;
110     offset &= ~1u;
111     uintptr_t scopeStart = ucbp->pr_cache.fnstart + offset;
112     uintptr_t scopeEnd = scopeStart + length;
113     uintptr_t pc = _Unwind_GetIP(context);
114     bool isInScope = (scopeStart <= pc) && (pc < scopeEnd);
115 
116     switch (kind) {
117       case Descriptor::CLEANUP: {
118         // TODO(ajwong): Handle cleanup descriptors.
119         break;
120       }
121       case Descriptor::FUNC: {
122         // TODO(ajwong): Handle function descriptors.
123         break;
124       }
125       case Descriptor::CATCH: {
126         // Catch descriptors require gobbling one more word.
127         uint32_t landing_pad;
128         descriptor = getNextWord(descriptor, &landing_pad);
129 
130         if (isInScope) {
131           // TODO(ajwong): This is only phase1 compatible logic. Implement
132           // phase2.
133           landing_pad = signExtendPrel31(landing_pad & ~0x80000000);
134           if (landing_pad == 0xffffffff) {
135             return _URC_HANDLER_FOUND;
136           } else if (landing_pad == 0xfffffffe) {
137             return _URC_FAILURE;
138           } else {
139             /*
140             bool is_reference_type = landing_pad & 0x80000000;
141             void* matched_object;
142             if (__cxxabiv1::__cxa_type_match(
143                     ucbp, reinterpret_cast<const std::type_info *>(landing_pad),
144                     is_reference_type,
145                     &matched_object) != __cxxabiv1::ctm_failed)
146                 return _URC_HANDLER_FOUND;
147                 */
148             _LIBUNWIND_ABORT("Type matching not implemented");
149           }
150         }
151         break;
152       }
153       default:
154         _LIBUNWIND_ABORT("Invalid descriptor kind found.");
155     }
156 
157     getNextWord(descriptor, &descriptorWord);
158   }
159 
160   return _URC_CONTINUE_UNWIND;
161 }
162 
163 static _Unwind_Reason_Code unwindOneFrame(_Unwind_State state,
164                                           _Unwind_Control_Block* ucbp,
165                                           struct _Unwind_Context* context) {
166   // Read the compact model EHT entry's header # 6.3
167   const uint32_t* unwindingData = ucbp->pr_cache.ehtp;
168   assert((*unwindingData & 0xf0000000) == 0x80000000 && "Must be a compact entry");
169   Descriptor::Format format =
170       static_cast<Descriptor::Format>((*unwindingData & 0x0f000000) >> 24);
171 
172   const char *lsda =
173       reinterpret_cast<const char *>(_Unwind_GetLanguageSpecificData(context));
174 
175   // Handle descriptors before unwinding so they are processed in the context
176   // of the correct stack frame.
177   _Unwind_Reason_Code result =
178       ProcessDescriptors(state, ucbp, context, format, lsda,
179                          ucbp->pr_cache.additional);
180 
181   if (result != _URC_CONTINUE_UNWIND)
182     return result;
183 
184   if (unw_step(reinterpret_cast<unw_cursor_t*>(context)) != UNW_STEP_SUCCESS)
185     return _URC_FAILURE;
186   return _URC_CONTINUE_UNWIND;
187 }
188 
189 // Generates mask discriminator for _Unwind_VRS_Pop, e.g. for _UVRSC_CORE /
190 // _UVRSD_UINT32.
191 uint32_t RegisterMask(uint8_t start, uint8_t count_minus_one) {
192   return ((1U << (count_minus_one + 1)) - 1) << start;
193 }
194 
195 // Generates mask discriminator for _Unwind_VRS_Pop, e.g. for _UVRSC_VFP /
196 // _UVRSD_DOUBLE.
197 uint32_t RegisterRange(uint8_t start, uint8_t count_minus_one) {
198   return ((uint32_t)start << 16) | ((uint32_t)count_minus_one + 1);
199 }
200 
201 } // end anonymous namespace
202 
203 /**
204  * Decodes an EHT entry.
205  *
206  * @param data Pointer to EHT.
207  * @param[out] off Offset from return value (in bytes) to begin interpretation.
208  * @param[out] len Number of bytes in unwind code.
209  * @return Pointer to beginning of unwind code.
210  */
211 extern "C" const uint32_t*
212 decode_eht_entry(const uint32_t* data, size_t* off, size_t* len) {
213   if ((*data & 0x80000000) == 0) {
214     // 6.2: Generic Model
215     //
216     // EHT entry is a prel31 pointing to the PR, followed by data understood
217     // only by the personality routine. Fortunately, all existing assembler
218     // implementations, including GNU assembler, LLVM integrated assembler,
219     // and ARM assembler, assume that the unwind opcodes come after the
220     // personality rountine address.
221     *off = 1; // First byte is size data.
222     *len = (((data[1] >> 24) & 0xff) + 1) * 4;
223     data++; // Skip the first word, which is the prel31 offset.
224   } else {
225     // 6.3: ARM Compact Model
226     //
227     // EHT entries here correspond to the __aeabi_unwind_cpp_pr[012] PRs indeded
228     // by format:
229     Descriptor::Format format =
230         static_cast<Descriptor::Format>((*data & 0x0f000000) >> 24);
231     switch (format) {
232       case Descriptor::SU16:
233         *len = 4;
234         *off = 1;
235         break;
236       case Descriptor::LU16:
237       case Descriptor::LU32:
238         *len = 4 + 4 * ((*data & 0x00ff0000) >> 16);
239         *off = 2;
240         break;
241       default:
242         return nullptr;
243     }
244   }
245   return data;
246 }
247 
248 _Unwind_Reason_Code _Unwind_VRS_Interpret(
249     _Unwind_Context* context,
250     const uint32_t* data,
251     size_t offset,
252     size_t len) {
253   bool wrotePC = false;
254   bool finish = false;
255   while (offset < len && !finish) {
256     uint8_t byte = getByte(data, offset++);
257     if ((byte & 0x80) == 0) {
258       uint32_t sp;
259       _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp);
260       if (byte & 0x40)
261         sp -= (((uint32_t)byte & 0x3f) << 2) + 4;
262       else
263         sp += ((uint32_t)byte << 2) + 4;
264       _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp);
265     } else {
266       switch (byte & 0xf0) {
267         case 0x80: {
268           if (offset >= len)
269             return _URC_FAILURE;
270           uint32_t registers =
271               (((uint32_t)byte & 0x0f) << 12) |
272               (((uint32_t)getByte(data, offset++)) << 4);
273           if (!registers)
274             return _URC_FAILURE;
275           if (registers & (1 << 15))
276             wrotePC = true;
277           _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
278           break;
279         }
280         case 0x90: {
281           uint8_t reg = byte & 0x0f;
282           if (reg == 13 || reg == 15)
283             return _URC_FAILURE;
284           uint32_t sp;
285           _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_R0 + reg,
286                           _UVRSD_UINT32, &sp);
287           _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
288                           &sp);
289           break;
290         }
291         case 0xa0: {
292           uint32_t registers = RegisterMask(4, byte & 0x07);
293           if (byte & 0x08)
294             registers |= 1 << 14;
295           _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
296           break;
297         }
298         case 0xb0: {
299           switch (byte) {
300             case 0xb0:
301               finish = true;
302               break;
303             case 0xb1: {
304               if (offset >= len)
305                 return _URC_FAILURE;
306               uint8_t registers = getByte(data, offset++);
307               if (registers & 0xf0 || !registers)
308                 return _URC_FAILURE;
309               _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
310               break;
311             }
312             case 0xb2: {
313               uint32_t addend = 0;
314               uint32_t shift = 0;
315               // This decodes a uleb128 value.
316               while (true) {
317                 if (offset >= len)
318                   return _URC_FAILURE;
319                 uint32_t v = getByte(data, offset++);
320                 addend |= (v & 0x7f) << shift;
321                 if ((v & 0x80) == 0)
322                   break;
323                 shift += 7;
324               }
325               uint32_t sp;
326               _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
327                               &sp);
328               sp += 0x204 + (addend << 2);
329               _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
330                               &sp);
331               break;
332             }
333             case 0xb3: {
334               uint8_t v = getByte(data, offset++);
335               _Unwind_VRS_Pop(context, _UVRSC_VFP,
336                               RegisterRange(static_cast<uint8_t>(v >> 4),
337                                             v & 0x0f), _UVRSD_VFPX);
338               break;
339             }
340             case 0xb4:
341             case 0xb5:
342             case 0xb6:
343             case 0xb7:
344               return _URC_FAILURE;
345             default:
346               _Unwind_VRS_Pop(context, _UVRSC_VFP,
347                               RegisterRange(8, byte & 0x07), _UVRSD_VFPX);
348               break;
349           }
350           break;
351         }
352         case 0xc0: {
353           switch (byte) {
354 #if defined(__ARM_WMMX)
355             case 0xc0:
356             case 0xc1:
357             case 0xc2:
358             case 0xc3:
359             case 0xc4:
360             case 0xc5:
361               _Unwind_VRS_Pop(context, _UVRSC_WMMXD,
362                               RegisterRange(10, byte & 0x7), _UVRSD_DOUBLE);
363               break;
364             case 0xc6: {
365               uint8_t v = getByte(data, offset++);
366               uint8_t start = static_cast<uint8_t>(v >> 4);
367               uint8_t count_minus_one = v & 0xf;
368               if (start + count_minus_one >= 16)
369                 return _URC_FAILURE;
370               _Unwind_VRS_Pop(context, _UVRSC_WMMXD,
371                               RegisterRange(start, count_minus_one),
372                               _UVRSD_DOUBLE);
373               break;
374             }
375             case 0xc7: {
376               uint8_t v = getByte(data, offset++);
377               if (!v || v & 0xf0)
378                 return _URC_FAILURE;
379               _Unwind_VRS_Pop(context, _UVRSC_WMMXC, v, _UVRSD_DOUBLE);
380               break;
381             }
382 #endif
383             case 0xc8:
384             case 0xc9: {
385               uint8_t v = getByte(data, offset++);
386               uint8_t start =
387                   static_cast<uint8_t>(((byte == 0xc8) ? 16 : 0) + (v >> 4));
388               uint8_t count_minus_one = v & 0xf;
389               if (start + count_minus_one >= 32)
390                 return _URC_FAILURE;
391               _Unwind_VRS_Pop(context, _UVRSC_VFP,
392                               RegisterRange(start, count_minus_one),
393                               _UVRSD_DOUBLE);
394               break;
395             }
396             default:
397               return _URC_FAILURE;
398           }
399           break;
400         }
401         case 0xd0: {
402           if (byte & 0x08)
403             return _URC_FAILURE;
404           _Unwind_VRS_Pop(context, _UVRSC_VFP, RegisterRange(8, byte & 0x7),
405                           _UVRSD_DOUBLE);
406           break;
407         }
408         default:
409           return _URC_FAILURE;
410       }
411     }
412   }
413   if (!wrotePC) {
414     uint32_t lr;
415     _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_LR, _UVRSD_UINT32, &lr);
416     _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_IP, _UVRSD_UINT32, &lr);
417   }
418   return _URC_CONTINUE_UNWIND;
419 }
420 
421 extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr0(
422     _Unwind_State state,
423     _Unwind_Control_Block *ucbp,
424     _Unwind_Context *context) {
425   return unwindOneFrame(state, ucbp, context);
426 }
427 
428 extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr1(
429     _Unwind_State state,
430     _Unwind_Control_Block *ucbp,
431     _Unwind_Context *context) {
432   return unwindOneFrame(state, ucbp, context);
433 }
434 
435 extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr2(
436     _Unwind_State state,
437     _Unwind_Control_Block *ucbp,
438     _Unwind_Context *context) {
439   return unwindOneFrame(state, ucbp, context);
440 }
441 
442 static _Unwind_Reason_Code
443 unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception *exception_object) {
444   // EHABI #7.3 discusses preserving the VRS in a "temporary VRS" during
445   // phase 1 and then restoring it to the "primary VRS" for phase 2. The
446   // effect is phase 2 doesn't see any of the VRS manipulations from phase 1.
447   // In this implementation, the phases don't share the VRS backing store.
448   // Instead, they are passed the original |uc| and they create a new VRS
449   // from scratch thus achieving the same effect.
450   unw_init_local(cursor, uc);
451 
452   // Walk each frame looking for a place to stop.
453   for (bool handlerNotFound = true; handlerNotFound;) {
454 
455     // See if frame has code to run (has personality routine).
456     unw_proc_info_t frameInfo;
457     if (unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
458       _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): unw_get_proc_info "
459                                  "failed => _URC_FATAL_PHASE1_ERROR",
460                                  static_cast<void *>(exception_object));
461       return _URC_FATAL_PHASE1_ERROR;
462     }
463 
464     // When tracing, print state information.
465     if (_LIBUNWIND_TRACING_UNWINDING) {
466       char functionBuf[512];
467       const char *functionName = functionBuf;
468       unw_word_t offset;
469       if ((unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
470                              &offset) != UNW_ESUCCESS) ||
471           (frameInfo.start_ip + offset > frameInfo.end_ip))
472         functionName = ".anonymous.";
473       unw_word_t pc;
474       unw_get_reg(cursor, UNW_REG_IP, &pc);
475       _LIBUNWIND_TRACE_UNWINDING(
476           "unwind_phase1(ex_ojb=%p): pc=0x%llX, start_ip=0x%llX, func=%s, "
477           "lsda=0x%llX, personality=0x%llX",
478           static_cast<void *>(exception_object), (long long)pc,
479           (long long)frameInfo.start_ip, functionName,
480           (long long)frameInfo.lsda, (long long)frameInfo.handler);
481     }
482 
483     // If there is a personality routine, ask it if it will want to stop at
484     // this frame.
485     if (frameInfo.handler != 0) {
486       __personality_routine p =
487           (__personality_routine)(long)(frameInfo.handler);
488       _LIBUNWIND_TRACE_UNWINDING(
489           "unwind_phase1(ex_ojb=%p): calling personality function %p",
490           static_cast<void *>(exception_object),
491           reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(p)));
492       struct _Unwind_Context *context = (struct _Unwind_Context *)(cursor);
493       exception_object->pr_cache.fnstart = frameInfo.start_ip;
494       exception_object->pr_cache.ehtp =
495           (_Unwind_EHT_Header *)frameInfo.unwind_info;
496       exception_object->pr_cache.additional = frameInfo.flags;
497       _Unwind_Reason_Code personalityResult =
498           (*p)(_US_VIRTUAL_UNWIND_FRAME, exception_object, context);
499       _LIBUNWIND_TRACE_UNWINDING(
500           "unwind_phase1(ex_ojb=%p): personality result %d start_ip %x ehtp %p "
501           "additional %x",
502           static_cast<void *>(exception_object), personalityResult,
503           exception_object->pr_cache.fnstart,
504           static_cast<void *>(exception_object->pr_cache.ehtp),
505           exception_object->pr_cache.additional);
506       switch (personalityResult) {
507       case _URC_HANDLER_FOUND:
508         // found a catch clause or locals that need destructing in this frame
509         // stop search and remember stack pointer at the frame
510         handlerNotFound = false;
511         // p should have initialized barrier_cache. EHABI #7.3.5
512         _LIBUNWIND_TRACE_UNWINDING(
513             "unwind_phase1(ex_ojb=%p): _URC_HANDLER_FOUND",
514             static_cast<void *>(exception_object));
515         return _URC_NO_REASON;
516 
517       case _URC_CONTINUE_UNWIND:
518         _LIBUNWIND_TRACE_UNWINDING(
519             "unwind_phase1(ex_ojb=%p): _URC_CONTINUE_UNWIND",
520             static_cast<void *>(exception_object));
521         // continue unwinding
522         break;
523 
524       // EHABI #7.3.3
525       case _URC_FAILURE:
526         return _URC_FAILURE;
527 
528       default:
529         // something went wrong
530         _LIBUNWIND_TRACE_UNWINDING(
531             "unwind_phase1(ex_ojb=%p): _URC_FATAL_PHASE1_ERROR",
532             static_cast<void *>(exception_object));
533         return _URC_FATAL_PHASE1_ERROR;
534       }
535     }
536   }
537   return _URC_NO_REASON;
538 }
539 
540 static _Unwind_Reason_Code unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor,
541                                          _Unwind_Exception *exception_object,
542                                          bool resume) {
543   // See comment at the start of unwind_phase1 regarding VRS integrity.
544   unw_init_local(cursor, uc);
545 
546   _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p)",
547                              static_cast<void *>(exception_object));
548   int frame_count = 0;
549 
550   // Walk each frame until we reach where search phase said to stop.
551   while (true) {
552     // Ask libunwind to get next frame (skip over first which is
553     // _Unwind_RaiseException or _Unwind_Resume).
554     //
555     // Resume only ever makes sense for 1 frame.
556     _Unwind_State state =
557         resume ? _US_UNWIND_FRAME_RESUME : _US_UNWIND_FRAME_STARTING;
558     if (resume && frame_count == 1) {
559       // On a resume, first unwind the _Unwind_Resume() frame. The next frame
560       // is now the landing pad for the cleanup from a previous execution of
561       // phase2. To continue unwindingly correctly, replace VRS[15] with the
562       // IP of the frame that the previous run of phase2 installed the context
563       // for. After this, continue unwinding as if normal.
564       //
565       // See #7.4.6 for details.
566       unw_set_reg(cursor, UNW_REG_IP,
567                   exception_object->unwinder_cache.reserved2);
568       resume = false;
569     }
570 
571     // Get info about this frame.
572     unw_word_t sp;
573     unw_proc_info_t frameInfo;
574     unw_get_reg(cursor, UNW_REG_SP, &sp);
575     if (unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
576       _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): unw_get_proc_info "
577                                  "failed => _URC_FATAL_PHASE2_ERROR",
578                                  static_cast<void *>(exception_object));
579       return _URC_FATAL_PHASE2_ERROR;
580     }
581 
582     // When tracing, print state information.
583     if (_LIBUNWIND_TRACING_UNWINDING) {
584       char functionBuf[512];
585       const char *functionName = functionBuf;
586       unw_word_t offset;
587       if ((unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
588                              &offset) != UNW_ESUCCESS) ||
589           (frameInfo.start_ip + offset > frameInfo.end_ip))
590         functionName = ".anonymous.";
591       _LIBUNWIND_TRACE_UNWINDING(
592           "unwind_phase2(ex_ojb=%p): start_ip=0x%llX, func=%s, sp=0x%llX, "
593           "lsda=0x%llX, personality=0x%llX",
594           static_cast<void *>(exception_object), (long long)frameInfo.start_ip,
595           functionName, (long long)sp, (long long)frameInfo.lsda,
596           (long long)frameInfo.handler);
597     }
598 
599     // If there is a personality routine, tell it we are unwinding.
600     if (frameInfo.handler != 0) {
601       __personality_routine p =
602           (__personality_routine)(long)(frameInfo.handler);
603       struct _Unwind_Context *context = (struct _Unwind_Context *)(cursor);
604       // EHABI #7.2
605       exception_object->pr_cache.fnstart = frameInfo.start_ip;
606       exception_object->pr_cache.ehtp =
607           (_Unwind_EHT_Header *)frameInfo.unwind_info;
608       exception_object->pr_cache.additional = frameInfo.flags;
609       _Unwind_Reason_Code personalityResult =
610           (*p)(state, exception_object, context);
611       switch (personalityResult) {
612       case _URC_CONTINUE_UNWIND:
613         // Continue unwinding
614         _LIBUNWIND_TRACE_UNWINDING(
615             "unwind_phase2(ex_ojb=%p): _URC_CONTINUE_UNWIND",
616             static_cast<void *>(exception_object));
617         // EHABI #7.2
618         if (sp == exception_object->barrier_cache.sp) {
619           // Phase 1 said we would stop at this frame, but we did not...
620           _LIBUNWIND_ABORT("during phase1 personality function said it would "
621                            "stop here, but now in phase2 it did not stop here");
622         }
623         break;
624       case _URC_INSTALL_CONTEXT:
625         _LIBUNWIND_TRACE_UNWINDING(
626             "unwind_phase2(ex_ojb=%p): _URC_INSTALL_CONTEXT",
627             static_cast<void *>(exception_object));
628         // Personality routine says to transfer control to landing pad.
629         // We may get control back if landing pad calls _Unwind_Resume().
630         if (_LIBUNWIND_TRACING_UNWINDING) {
631           unw_word_t pc;
632           unw_get_reg(cursor, UNW_REG_IP, &pc);
633           unw_get_reg(cursor, UNW_REG_SP, &sp);
634           _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): re-entering "
635                                      "user code with ip=0x%llX, sp=0x%llX",
636                                      static_cast<void *>(exception_object),
637                                      (long long)pc, (long long)sp);
638         }
639 
640         {
641           // EHABI #7.4.1 says we need to preserve pc for when _Unwind_Resume
642           // is called back, to find this same frame.
643           unw_word_t pc;
644           unw_get_reg(cursor, UNW_REG_IP, &pc);
645           exception_object->unwinder_cache.reserved2 = (uint32_t)pc;
646         }
647         unw_resume(cursor);
648         // unw_resume() only returns if there was an error.
649         return _URC_FATAL_PHASE2_ERROR;
650 
651       // # EHABI #7.4.3
652       case _URC_FAILURE:
653         abort();
654 
655       default:
656         // Personality routine returned an unknown result code.
657         _LIBUNWIND_DEBUG_LOG("personality function returned unknown result %d",
658                       personalityResult);
659         return _URC_FATAL_PHASE2_ERROR;
660       }
661     }
662     frame_count++;
663   }
664 
665   // Clean up phase did not resume at the frame that the search phase
666   // said it would...
667   return _URC_FATAL_PHASE2_ERROR;
668 }
669 
670 /// Called by __cxa_throw.  Only returns if there is a fatal error.
671 _LIBUNWIND_EXPORT _Unwind_Reason_Code
672 _Unwind_RaiseException(_Unwind_Exception *exception_object) {
673   _LIBUNWIND_TRACE_API("_Unwind_RaiseException(ex_obj=%p)",
674                        static_cast<void *>(exception_object));
675   unw_context_t uc;
676   unw_cursor_t cursor;
677   unw_getcontext(&uc);
678 
679   // This field for is for compatibility with GCC to say this isn't a forced
680   // unwind. EHABI #7.2
681   exception_object->unwinder_cache.reserved1 = 0;
682 
683   // phase 1: the search phase
684   _Unwind_Reason_Code phase1 = unwind_phase1(&uc, &cursor, exception_object);
685   if (phase1 != _URC_NO_REASON)
686     return phase1;
687 
688   // phase 2: the clean up phase
689   return unwind_phase2(&uc, &cursor, exception_object, false);
690 }
691 
692 _LIBUNWIND_EXPORT void _Unwind_Complete(_Unwind_Exception* exception_object) {
693   // This is to be called when exception handling completes to give us a chance
694   // to perform any housekeeping. EHABI #7.2. But we have nothing to do here.
695   (void)exception_object;
696 }
697 
698 /// When _Unwind_RaiseException() is in phase2, it hands control
699 /// to the personality function at each frame.  The personality
700 /// may force a jump to a landing pad in that function, the landing
701 /// pad code may then call _Unwind_Resume() to continue with the
702 /// unwinding.  Note: the call to _Unwind_Resume() is from compiler
703 /// geneated user code.  All other _Unwind_* routines are called
704 /// by the C++ runtime __cxa_* routines.
705 ///
706 /// Note: re-throwing an exception (as opposed to continuing the unwind)
707 /// is implemented by having the code call __cxa_rethrow() which
708 /// in turn calls _Unwind_Resume_or_Rethrow().
709 _LIBUNWIND_EXPORT void
710 _Unwind_Resume(_Unwind_Exception *exception_object) {
711   _LIBUNWIND_TRACE_API("_Unwind_Resume(ex_obj=%p)",
712                        static_cast<void *>(exception_object));
713   unw_context_t uc;
714   unw_cursor_t cursor;
715   unw_getcontext(&uc);
716 
717   // _Unwind_RaiseException on EHABI will always set the reserved1 field to 0,
718   // which is in the same position as private_1 below.
719   // TODO(ajwong): Who wronte the above? Why is it true?
720   unwind_phase2(&uc, &cursor, exception_object, true);
721 
722   // Clients assume _Unwind_Resume() does not return, so all we can do is abort.
723   _LIBUNWIND_ABORT("_Unwind_Resume() can't return");
724 }
725 
726 /// Called by personality handler during phase 2 to get LSDA for current frame.
727 _LIBUNWIND_EXPORT uintptr_t
728 _Unwind_GetLanguageSpecificData(struct _Unwind_Context *context) {
729   unw_cursor_t *cursor = (unw_cursor_t *)context;
730   unw_proc_info_t frameInfo;
731   uintptr_t result = 0;
732   if (unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
733     result = (uintptr_t)frameInfo.lsda;
734   _LIBUNWIND_TRACE_API(
735       "_Unwind_GetLanguageSpecificData(context=%p) => 0x%llx",
736       static_cast<void *>(context), (long long)result);
737   return result;
738 }
739 
740 static uint64_t ValueAsBitPattern(_Unwind_VRS_DataRepresentation representation,
741                                   void* valuep) {
742   uint64_t value = 0;
743   switch (representation) {
744     case _UVRSD_UINT32:
745     case _UVRSD_FLOAT:
746       memcpy(&value, valuep, sizeof(uint32_t));
747       break;
748 
749     case _UVRSD_VFPX:
750     case _UVRSD_UINT64:
751     case _UVRSD_DOUBLE:
752       memcpy(&value, valuep, sizeof(uint64_t));
753       break;
754   }
755   return value;
756 }
757 
758 _Unwind_VRS_Result
759 _Unwind_VRS_Set(_Unwind_Context *context, _Unwind_VRS_RegClass regclass,
760                 uint32_t regno, _Unwind_VRS_DataRepresentation representation,
761                 void *valuep) {
762   _LIBUNWIND_TRACE_API("_Unwind_VRS_Set(context=%p, regclass=%d, reg=%d, "
763                        "rep=%d, value=0x%llX)",
764                        static_cast<void *>(context), regclass, regno,
765                        representation,
766                        ValueAsBitPattern(representation, valuep));
767   unw_cursor_t *cursor = (unw_cursor_t *)context;
768   switch (regclass) {
769     case _UVRSC_CORE:
770       if (representation != _UVRSD_UINT32 || regno > 15)
771         return _UVRSR_FAILED;
772       return unw_set_reg(cursor, (unw_regnum_t)(UNW_ARM_R0 + regno),
773                          *(unw_word_t *)valuep) == UNW_ESUCCESS
774                  ? _UVRSR_OK
775                  : _UVRSR_FAILED;
776     case _UVRSC_VFP:
777       if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
778         return _UVRSR_FAILED;
779       if (representation == _UVRSD_VFPX) {
780         // Can only touch d0-15 with FSTMFDX.
781         if (regno > 15)
782           return _UVRSR_FAILED;
783         unw_save_vfp_as_X(cursor);
784       } else {
785         if (regno > 31)
786           return _UVRSR_FAILED;
787       }
788       return unw_set_fpreg(cursor, (unw_regnum_t)(UNW_ARM_D0 + regno),
789                            *(unw_fpreg_t *)valuep) == UNW_ESUCCESS
790                  ? _UVRSR_OK
791                  : _UVRSR_FAILED;
792 #if defined(__ARM_WMMX)
793     case _UVRSC_WMMXC:
794       if (representation != _UVRSD_UINT32 || regno > 3)
795         return _UVRSR_FAILED;
796       return unw_set_reg(cursor, (unw_regnum_t)(UNW_ARM_WC0 + regno),
797                          *(unw_word_t *)valuep) == UNW_ESUCCESS
798                  ? _UVRSR_OK
799                  : _UVRSR_FAILED;
800     case _UVRSC_WMMXD:
801       if (representation != _UVRSD_DOUBLE || regno > 31)
802         return _UVRSR_FAILED;
803       return unw_set_fpreg(cursor, (unw_regnum_t)(UNW_ARM_WR0 + regno),
804                            *(unw_fpreg_t *)valuep) == UNW_ESUCCESS
805                  ? _UVRSR_OK
806                  : _UVRSR_FAILED;
807 #else
808     case _UVRSC_WMMXC:
809     case _UVRSC_WMMXD:
810       break;
811 #endif
812   }
813   _LIBUNWIND_ABORT("unsupported register class");
814 }
815 
816 static _Unwind_VRS_Result
817 _Unwind_VRS_Get_Internal(_Unwind_Context *context,
818                          _Unwind_VRS_RegClass regclass, uint32_t regno,
819                          _Unwind_VRS_DataRepresentation representation,
820                          void *valuep) {
821   unw_cursor_t *cursor = (unw_cursor_t *)context;
822   switch (regclass) {
823     case _UVRSC_CORE:
824       if (representation != _UVRSD_UINT32 || regno > 15)
825         return _UVRSR_FAILED;
826       return unw_get_reg(cursor, (unw_regnum_t)(UNW_ARM_R0 + regno),
827                          (unw_word_t *)valuep) == UNW_ESUCCESS
828                  ? _UVRSR_OK
829                  : _UVRSR_FAILED;
830     case _UVRSC_VFP:
831       if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
832         return _UVRSR_FAILED;
833       if (representation == _UVRSD_VFPX) {
834         // Can only touch d0-15 with FSTMFDX.
835         if (regno > 15)
836           return _UVRSR_FAILED;
837         unw_save_vfp_as_X(cursor);
838       } else {
839         if (regno > 31)
840           return _UVRSR_FAILED;
841       }
842       return unw_get_fpreg(cursor, (unw_regnum_t)(UNW_ARM_D0 + regno),
843                            (unw_fpreg_t *)valuep) == UNW_ESUCCESS
844                  ? _UVRSR_OK
845                  : _UVRSR_FAILED;
846 #if defined(__ARM_WMMX)
847     case _UVRSC_WMMXC:
848       if (representation != _UVRSD_UINT32 || regno > 3)
849         return _UVRSR_FAILED;
850       return unw_get_reg(cursor, (unw_regnum_t)(UNW_ARM_WC0 + regno),
851                          (unw_word_t *)valuep) == UNW_ESUCCESS
852                  ? _UVRSR_OK
853                  : _UVRSR_FAILED;
854     case _UVRSC_WMMXD:
855       if (representation != _UVRSD_DOUBLE || regno > 31)
856         return _UVRSR_FAILED;
857       return unw_get_fpreg(cursor, (unw_regnum_t)(UNW_ARM_WR0 + regno),
858                            (unw_fpreg_t *)valuep) == UNW_ESUCCESS
859                  ? _UVRSR_OK
860                  : _UVRSR_FAILED;
861 #else
862     case _UVRSC_WMMXC:
863     case _UVRSC_WMMXD:
864       break;
865 #endif
866   }
867   _LIBUNWIND_ABORT("unsupported register class");
868 }
869 
870 _Unwind_VRS_Result _Unwind_VRS_Get(
871     _Unwind_Context *context,
872     _Unwind_VRS_RegClass regclass,
873     uint32_t regno,
874     _Unwind_VRS_DataRepresentation representation,
875     void *valuep) {
876   _Unwind_VRS_Result result =
877       _Unwind_VRS_Get_Internal(context, regclass, regno, representation,
878                                valuep);
879   _LIBUNWIND_TRACE_API("_Unwind_VRS_Get(context=%p, regclass=%d, reg=%d, "
880                        "rep=%d, value=0x%llX, result = %d)",
881                        static_cast<void *>(context), regclass, regno,
882                        representation,
883                        ValueAsBitPattern(representation, valuep), result);
884   return result;
885 }
886 
887 _Unwind_VRS_Result
888 _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass,
889                 uint32_t discriminator,
890                 _Unwind_VRS_DataRepresentation representation) {
891   _LIBUNWIND_TRACE_API("_Unwind_VRS_Pop(context=%p, regclass=%d, "
892                        "discriminator=%d, representation=%d)",
893                        static_cast<void *>(context), regclass, discriminator,
894                        representation);
895   switch (regclass) {
896     case _UVRSC_WMMXC:
897 #if !defined(__ARM_WMMX)
898       break;
899 #endif
900     case _UVRSC_CORE: {
901       if (representation != _UVRSD_UINT32)
902         return _UVRSR_FAILED;
903       // When popping SP from the stack, we don't want to override it from the
904       // computed new stack location. See EHABI #7.5.4 table 3.
905       bool poppedSP = false;
906       uint32_t* sp;
907       if (_Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP,
908                           _UVRSD_UINT32, &sp) != _UVRSR_OK) {
909         return _UVRSR_FAILED;
910       }
911       for (uint32_t i = 0; i < 16; ++i) {
912         if (!(discriminator & static_cast<uint32_t>(1 << i)))
913           continue;
914         uint32_t value = *sp++;
915         if (regclass == _UVRSC_CORE && i == 13)
916           poppedSP = true;
917         if (_Unwind_VRS_Set(context, regclass, i,
918                             _UVRSD_UINT32, &value) != _UVRSR_OK) {
919           return _UVRSR_FAILED;
920         }
921       }
922       if (!poppedSP) {
923         return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP,
924                                _UVRSD_UINT32, &sp);
925       }
926       return _UVRSR_OK;
927     }
928     case _UVRSC_WMMXD:
929 #if !defined(__ARM_WMMX)
930       break;
931 #endif
932     case _UVRSC_VFP: {
933       if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
934         return _UVRSR_FAILED;
935       uint32_t first = discriminator >> 16;
936       uint32_t count = discriminator & 0xffff;
937       uint32_t end = first+count;
938       uint32_t* sp;
939       if (_Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP,
940                           _UVRSD_UINT32, &sp) != _UVRSR_OK) {
941         return _UVRSR_FAILED;
942       }
943       // For _UVRSD_VFPX, we're assuming the data is stored in FSTMX "standard
944       // format 1", which is equivalent to FSTMD + a padding word.
945       for (uint32_t i = first; i < end; ++i) {
946         // SP is only 32-bit aligned so don't copy 64-bit at a time.
947         uint64_t value = *sp++;
948         value |= ((uint64_t)(*sp++)) << 32;
949         if (_Unwind_VRS_Set(context, regclass, i, representation, &value) !=
950             _UVRSR_OK)
951           return _UVRSR_FAILED;
952       }
953       if (representation == _UVRSD_VFPX)
954         ++sp;
955       return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
956                              &sp);
957     }
958   }
959   _LIBUNWIND_ABORT("unsupported register class");
960 }
961 
962 /// Called by personality handler during phase 2 to find the start of the
963 /// function.
964 _LIBUNWIND_EXPORT uintptr_t
965 _Unwind_GetRegionStart(struct _Unwind_Context *context) {
966   unw_cursor_t *cursor = (unw_cursor_t *)context;
967   unw_proc_info_t frameInfo;
968   uintptr_t result = 0;
969   if (unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
970     result = (uintptr_t)frameInfo.start_ip;
971   _LIBUNWIND_TRACE_API("_Unwind_GetRegionStart(context=%p) => 0x%llX",
972                        static_cast<void *>(context), (long long)result);
973   return result;
974 }
975 
976 
977 /// Called by personality handler during phase 2 if a foreign exception
978 // is caught.
979 _LIBUNWIND_EXPORT void
980 _Unwind_DeleteException(_Unwind_Exception *exception_object) {
981   _LIBUNWIND_TRACE_API("_Unwind_DeleteException(ex_obj=%p)",
982                        static_cast<void *>(exception_object));
983   if (exception_object->exception_cleanup != NULL)
984     (*exception_object->exception_cleanup)(_URC_FOREIGN_EXCEPTION_CAUGHT,
985                                            exception_object);
986 }
987 
988 extern "C" _LIBUNWIND_EXPORT _Unwind_Reason_Code
989 __gnu_unwind_frame(_Unwind_Exception *exception_object,
990                    struct _Unwind_Context *context) {
991   unw_cursor_t *cursor = (unw_cursor_t *)context;
992   if (unw_step(cursor) != UNW_STEP_SUCCESS)
993     return _URC_FAILURE;
994   return _URC_OK;
995 }
996 
997 #endif  // _LIBUNWIND_ARM_EHABI
998