121526Sdavidn//===--------------------------- Unwind-EHABI.cpp -------------------------===//
225901Sgpalmer//
321526Sdavidn//                     The LLVM Compiler Infrastructure
421526Sdavidn//
521526Sdavidn// This file is dual licensed under the MIT and the University of Illinois Open
621526Sdavidn// Source Licenses. See LICENSE.TXT for details.
721526Sdavidn//
821526Sdavidn//
921526Sdavidn//  Implements ARM zero-cost C++ exceptions
1021526Sdavidn//
1121526Sdavidn//===----------------------------------------------------------------------===//
1242149Shoek
1321526Sdavidn#include "Unwind-EHABI.h"
1421526Sdavidn
1539375Smsmith#if _LIBUNWIND_ARM_EHABI
1639375Smsmith
1721526Sdavidn#include <stdbool.h>
1842149Shoek#include <stdint.h>
1921526Sdavidn#include <stdio.h>
2021526Sdavidn#include <stdlib.h>
2121526Sdavidn#include <string.h>
2221526Sdavidn
2321526Sdavidn#include <type_traits>
2421526Sdavidn
2521943Sdavidn#include "config.h"
2621526Sdavidn#include "libunwind.h"
2721526Sdavidn#include "libunwind_ext.h"
2839375Smsmith#include "unwind.h"
2939375Smsmith
3039375Smsmithnamespace {
3139375Smsmith
3239375Smsmith// Strange order: take words in order, but inside word, take from most to least
3339375Smsmith// signinficant byte.
3439375Smsmithuint8_t getByte(const uint32_t* data, size_t offset) {
3539375Smsmith  const uint8_t* byteData = reinterpret_cast<const uint8_t*>(data);
3639375Smsmith  return byteData[(offset & ~(size_t)0x03) + (3 - (offset & (size_t)0x03))];
3721538Sdavidn}
3821526Sdavidn
3939375Smsmithconst char* getNextWord(const char* data, uint32_t* out) {
4021526Sdavidn  *out = *reinterpret_cast<const uint32_t*>(data);
4121943Sdavidn  return data + 4;
4221538Sdavidn}
4339375Smsmith
4439375Smsmithconst char* getNextNibble(const char* data, uint32_t* out) {
4539375Smsmith  *out = *reinterpret_cast<const uint16_t*>(data);
4621538Sdavidn  return data + 2;
4739375Smsmith}
4839375Smsmith
4921538Sdavidnstruct Descriptor {
5039375Smsmith  // See # 9.2
5121526Sdavidn  typedef enum {
5239375Smsmith    SU16 = 0, // Short descriptor, 16-bit entries
5339375Smsmith    LU16 = 1, // Long descriptor,  16-bit entries
5439424Sdt    LU32 = 3, // Long descriptor,  32-bit entries
5539375Smsmith    RESERVED0 =  4, RESERVED1 =  5, RESERVED2  = 6,  RESERVED3  =  7,
5639375Smsmith    RESERVED4 =  8, RESERVED5 =  9, RESERVED6  = 10, RESERVED7  = 11,
5739375Smsmith    RESERVED8 = 12, RESERVED9 = 13, RESERVED10 = 14, RESERVED11 = 15
5839375Smsmith  } Format;
5921526Sdavidn
6021526Sdavidn  // See # 9.2
6139375Smsmith  typedef enum {
6221526Sdavidn    CLEANUP = 0x0,
6321526Sdavidn    FUNC    = 0x1,
6439375Smsmith    CATCH   = 0x2,
6539375Smsmith    INVALID = 0x4
6621526Sdavidn  } Kind;
6721526Sdavidn};
6839375Smsmith
6921526Sdavidn_Unwind_Reason_Code ProcessDescriptors(
7039375Smsmith    _Unwind_State state,
7139375Smsmith    _Unwind_Control_Block* ucbp,
7239375Smsmith    struct _Unwind_Context* context,
7321526Sdavidn    Descriptor::Format format,
7421526Sdavidn    const char* descriptorStart,
7521526Sdavidn    uint32_t flags) {
7639375Smsmith
7739375Smsmith  // EHT is inlined in the index using compact form. No descriptors. #5
7839375Smsmith  if (flags & 0x1)
7939375Smsmith    return _URC_CONTINUE_UNWIND;
8039375Smsmith
8139375Smsmith  // TODO: We should check the state here, and determine whether we need to
8239375Smsmith  // perform phase1 or phase2 unwinding.
8339375Smsmith  (void)state;
8439375Smsmith
8539375Smsmith  const char* descriptor = descriptorStart;
8639375Smsmith  uint32_t descriptorWord;
8721526Sdavidn  getNextWord(descriptor, &descriptorWord);
8839375Smsmith  while (descriptorWord) {
8939375Smsmith    // Read descriptor based on # 9.2.
9021526Sdavidn    uint32_t length;
9139375Smsmith    uint32_t offset;
9239375Smsmith    switch (format) {
9339375Smsmith      case Descriptor::LU32:
9421526Sdavidn        descriptor = getNextWord(descriptor, &length);
9539375Smsmith        descriptor = getNextWord(descriptor, &offset);
9639375Smsmith      case Descriptor::LU16:
9721526Sdavidn        descriptor = getNextNibble(descriptor, &length);
9821526Sdavidn        descriptor = getNextNibble(descriptor, &offset);
9939375Smsmith      default:
10039375Smsmith        assert(false);
10139375Smsmith        return _URC_FAILURE;
10221526Sdavidn    }
10339375Smsmith
10439375Smsmith    // See # 9.2 table for decoding the kind of descriptor. It's a 2-bit value.
10539375Smsmith    Descriptor::Kind kind =
10639375Smsmith        static_cast<Descriptor::Kind>((length & 0x1) | ((offset & 0x1) << 1));
10739375Smsmith
10839375Smsmith    // Clear off flag from last bit.
10939375Smsmith    length &= ~1u;
11039375Smsmith    offset &= ~1u;
11139375Smsmith    uintptr_t scopeStart = ucbp->pr_cache.fnstart + offset;
11239375Smsmith    uintptr_t scopeEnd = scopeStart + length;
11339375Smsmith    uintptr_t pc = _Unwind_GetIP(context);
11439375Smsmith    bool isInScope = (scopeStart <= pc) && (pc < scopeEnd);
11539375Smsmith
11639375Smsmith    switch (kind) {
11721526Sdavidn      case Descriptor::CLEANUP: {
11821526Sdavidn        // TODO(ajwong): Handle cleanup descriptors.
11939375Smsmith        break;
12039375Smsmith      }
12139375Smsmith      case Descriptor::FUNC: {
12239375Smsmith        // TODO(ajwong): Handle function descriptors.
12339375Smsmith        break;
12439375Smsmith      }
12539375Smsmith      case Descriptor::CATCH: {
12639375Smsmith        // Catch descriptors require gobbling one more word.
12739375Smsmith        uint32_t landing_pad;
12839375Smsmith        descriptor = getNextWord(descriptor, &landing_pad);
12939375Smsmith
13039375Smsmith        if (isInScope) {
13139375Smsmith          // TODO(ajwong): This is only phase1 compatible logic. Implement
13239375Smsmith          // phase2.
13339375Smsmith          landing_pad = signExtendPrel31(landing_pad & ~0x80000000);
13439375Smsmith          if (landing_pad == 0xffffffff) {
13539375Smsmith            return _URC_HANDLER_FOUND;
13639375Smsmith          } else if (landing_pad == 0xfffffffe) {
13739375Smsmith            return _URC_FAILURE;
13839375Smsmith          } else {
13939375Smsmith            /*
14039375Smsmith            bool is_reference_type = landing_pad & 0x80000000;
14139375Smsmith            void* matched_object;
14239375Smsmith            if (__cxxabiv1::__cxa_type_match(
14339375Smsmith                    ucbp, reinterpret_cast<const std::type_info *>(landing_pad),
14421526Sdavidn                    is_reference_type,
14521526Sdavidn                    &matched_object) != __cxxabiv1::ctm_failed)
14639375Smsmith                return _URC_HANDLER_FOUND;
14739375Smsmith                */
14839375Smsmith            _LIBUNWIND_ABORT("Type matching not implemented");
14939375Smsmith          }
15039375Smsmith        }
15139375Smsmith        break;
15239375Smsmith      }
15339375Smsmith      default:
15439375Smsmith        _LIBUNWIND_ABORT("Invalid descriptor kind found.");
15539375Smsmith    }
15639375Smsmith
15739375Smsmith    getNextWord(descriptor, &descriptorWord);
15839375Smsmith  }
15925369Sache
16025369Sache  return _URC_CONTINUE_UNWIND;
16139375Smsmith}
16239375Smsmith
16339375Smsmithstatic _Unwind_Reason_Code unwindOneFrame(_Unwind_State state,
16439375Smsmith                                          _Unwind_Control_Block* ucbp,
16539375Smsmith                                          struct _Unwind_Context* context) {
16639375Smsmith  // Read the compact model EHT entry's header # 6.3
16739375Smsmith  const uint32_t* unwindingData = ucbp->pr_cache.ehtp;
16839375Smsmith  assert((*unwindingData & 0xf0000000) == 0x80000000 && "Must be a compact entry");
16939375Smsmith  Descriptor::Format format =
17039375Smsmith      static_cast<Descriptor::Format>((*unwindingData & 0x0f000000) >> 24);
17139375Smsmith
17239375Smsmith  const char *lsda =
17339375Smsmith      reinterpret_cast<const char *>(_Unwind_GetLanguageSpecificData(context));
17439375Smsmith
17539375Smsmith  // Handle descriptors before unwinding so they are processed in the context
17639375Smsmith  // of the correct stack frame.
17739375Smsmith  _Unwind_Reason_Code result =
17839375Smsmith      ProcessDescriptors(state, ucbp, context, format, lsda,
17939375Smsmith                         ucbp->pr_cache.additional);
18039375Smsmith
18139375Smsmith  if (result != _URC_CONTINUE_UNWIND)
18239375Smsmith    return result;
18339375Smsmith
18439375Smsmith  if (unw_step(reinterpret_cast<unw_cursor_t*>(context)) != UNW_STEP_SUCCESS)
18539375Smsmith    return _URC_FAILURE;
18639375Smsmith  return _URC_CONTINUE_UNWIND;
18739375Smsmith}
18839375Smsmith
18939375Smsmith// Generates mask discriminator for _Unwind_VRS_Pop, e.g. for _UVRSC_CORE /
19039375Smsmith// _UVRSD_UINT32.
19139375Smsmithuint32_t RegisterMask(uint8_t start, uint8_t count_minus_one) {
19239375Smsmith  return ((1U << (count_minus_one + 1)) - 1) << start;
19339375Smsmith}
19439375Smsmith
19539375Smsmith// Generates mask discriminator for _Unwind_VRS_Pop, e.g. for _UVRSC_VFP /
19639375Smsmith// _UVRSD_DOUBLE.
19739375Smsmithuint32_t RegisterRange(uint8_t start, uint8_t count_minus_one) {
19839375Smsmith  return ((uint32_t)start << 16) | ((uint32_t)count_minus_one + 1);
19939375Smsmith}
20039375Smsmith
20139375Smsmith} // end anonymous namespace
20239375Smsmith
20339375Smsmith/**
20439375Smsmith * Decodes an EHT entry.
20539375Smsmith *
20639375Smsmith * @param data Pointer to EHT.
20739375Smsmith * @param[out] off Offset from return value (in bytes) to begin interpretation.
20839375Smsmith * @param[out] len Number of bytes in unwind code.
20939375Smsmith * @return Pointer to beginning of unwind code.
21039375Smsmith */
21139375Smsmithextern "C" const uint32_t*
21239375Smsmithdecode_eht_entry(const uint32_t* data, size_t* off, size_t* len) {
21339375Smsmith  if ((*data & 0x80000000) == 0) {
21439375Smsmith    // 6.2: Generic Model
21539375Smsmith    //
21639375Smsmith    // EHT entry is a prel31 pointing to the PR, followed by data understood
21739375Smsmith    // only by the personality routine. Fortunately, all existing assembler
21839375Smsmith    // implementations, including GNU assembler, LLVM integrated assembler,
21939375Smsmith    // and ARM assembler, assume that the unwind opcodes come after the
22039375Smsmith    // personality rountine address.
22139375Smsmith    *off = 1; // First byte is size data.
22239375Smsmith    *len = (((data[1] >> 24) & 0xff) + 1) * 4;
22339375Smsmith    data++; // Skip the first word, which is the prel31 offset.
22439375Smsmith  } else {
22539375Smsmith    // 6.3: ARM Compact Model
22639375Smsmith    //
22739375Smsmith    // EHT entries here correspond to the __aeabi_unwind_cpp_pr[012] PRs indeded
22839375Smsmith    // by format:
22939375Smsmith    Descriptor::Format format =
23039375Smsmith        static_cast<Descriptor::Format>((*data & 0x0f000000) >> 24);
23139375Smsmith    switch (format) {
23239375Smsmith      case Descriptor::SU16:
23339375Smsmith        *len = 4;
23439375Smsmith        *off = 1;
23539375Smsmith        break;
23639375Smsmith      case Descriptor::LU16:
23739375Smsmith      case Descriptor::LU32:
23839375Smsmith        *len = 4 + 4 * ((*data & 0x00ff0000) >> 16);
23939375Smsmith        *off = 2;
24039375Smsmith        break;
24139375Smsmith      default:
24239375Smsmith        return nullptr;
24339375Smsmith    }
24439375Smsmith  }
24539375Smsmith  return data;
24639375Smsmith}
24739375Smsmith
24839375Smsmith_Unwind_Reason_Code _Unwind_VRS_Interpret(
24939375Smsmith    _Unwind_Context* context,
25039375Smsmith    const uint32_t* data,
25139375Smsmith    size_t offset,
25239375Smsmith    size_t len) {
25339375Smsmith  bool wrotePC = false;
25439375Smsmith  bool finish = false;
25539375Smsmith  while (offset < len && !finish) {
25639375Smsmith    uint8_t byte = getByte(data, offset++);
25739375Smsmith    if ((byte & 0x80) == 0) {
25839375Smsmith      uint32_t sp;
25939375Smsmith      _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp);
26039375Smsmith      if (byte & 0x40)
26139375Smsmith        sp -= (((uint32_t)byte & 0x3f) << 2) + 4;
26239375Smsmith      else
26339375Smsmith        sp += ((uint32_t)byte << 2) + 4;
26439375Smsmith      _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp);
26539375Smsmith    } else {
26639375Smsmith      switch (byte & 0xf0) {
26739375Smsmith        case 0x80: {
26839375Smsmith          if (offset >= len)
26939375Smsmith            return _URC_FAILURE;
27039375Smsmith          uint32_t registers =
27139375Smsmith              (((uint32_t)byte & 0x0f) << 12) |
27239375Smsmith              (((uint32_t)getByte(data, offset++)) << 4);
27339375Smsmith          if (!registers)
27439375Smsmith            return _URC_FAILURE;
27539375Smsmith          if (registers & (1 << 15))
27639375Smsmith            wrotePC = true;
27739375Smsmith          _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
27839375Smsmith          break;
27939375Smsmith        }
28039375Smsmith        case 0x90: {
28139375Smsmith          uint8_t reg = byte & 0x0f;
28239375Smsmith          if (reg == 13 || reg == 15)
28339375Smsmith            return _URC_FAILURE;
28439375Smsmith          uint32_t sp;
28539375Smsmith          _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_R0 + reg,
28639375Smsmith                          _UVRSD_UINT32, &sp);
28739375Smsmith          _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
28839375Smsmith                          &sp);
28939375Smsmith          break;
29039375Smsmith        }
29139375Smsmith        case 0xa0: {
29239375Smsmith          uint32_t registers = RegisterMask(4, byte & 0x07);
29339375Smsmith          if (byte & 0x08)
29439375Smsmith            registers |= 1 << 14;
29539375Smsmith          _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
29639375Smsmith          break;
29739375Smsmith        }
29839375Smsmith        case 0xb0: {
29939375Smsmith          switch (byte) {
30039375Smsmith            case 0xb0:
30139375Smsmith              finish = true;
30239375Smsmith              break;
30339375Smsmith            case 0xb1: {
30439375Smsmith              if (offset >= len)
30539375Smsmith                return _URC_FAILURE;
30639375Smsmith              uint8_t registers = getByte(data, offset++);
30739375Smsmith              if (registers & 0xf0 || !registers)
30839375Smsmith                return _URC_FAILURE;
30939375Smsmith              _Unwind_VRS_Pop(context, _UVRSC_CORE, registers, _UVRSD_UINT32);
31039375Smsmith              break;
31139375Smsmith            }
31239375Smsmith            case 0xb2: {
31339375Smsmith              uint32_t addend = 0;
31439375Smsmith              uint32_t shift = 0;
31539375Smsmith              // This decodes a uleb128 value.
31639375Smsmith              while (true) {
31739375Smsmith                if (offset >= len)
31839375Smsmith                  return _URC_FAILURE;
31939375Smsmith                uint32_t v = getByte(data, offset++);
32039375Smsmith                addend |= (v & 0x7f) << shift;
32139375Smsmith                if ((v & 0x80) == 0)
32239375Smsmith                  break;
32339375Smsmith                shift += 7;
32439375Smsmith              }
32539375Smsmith              uint32_t sp;
32639375Smsmith              _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
32742113Scwt                              &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            case 0xc0:
355            case 0xc1:
356            case 0xc2:
357            case 0xc3:
358            case 0xc4:
359            case 0xc5:
360              _Unwind_VRS_Pop(context, _UVRSC_WMMXD,
361                              RegisterRange(10, byte & 0x7), _UVRSD_DOUBLE);
362              break;
363            case 0xc6: {
364              uint8_t v = getByte(data, offset++);
365              uint8_t start = static_cast<uint8_t>(v >> 4);
366              uint8_t count_minus_one = v & 0xf;
367              if (start + count_minus_one >= 16)
368                return _URC_FAILURE;
369              _Unwind_VRS_Pop(context, _UVRSC_WMMXD,
370                              RegisterRange(start, count_minus_one),
371                              _UVRSD_DOUBLE);
372              break;
373            }
374            case 0xc7: {
375              uint8_t v = getByte(data, offset++);
376              if (!v || v & 0xf0)
377                return _URC_FAILURE;
378              _Unwind_VRS_Pop(context, _UVRSC_WMMXC, v, _UVRSD_DOUBLE);
379              break;
380            }
381            case 0xc8:
382            case 0xc9: {
383              uint8_t v = getByte(data, offset++);
384              uint8_t start =
385                  static_cast<uint8_t>(((byte == 0xc8) ? 16 : 0) + (v >> 4));
386              uint8_t count_minus_one = v & 0xf;
387              if (start + count_minus_one >= 32)
388                return _URC_FAILURE;
389              _Unwind_VRS_Pop(context, _UVRSC_VFP,
390                              RegisterRange(start, count_minus_one),
391                              _UVRSD_DOUBLE);
392              break;
393            }
394            default:
395              return _URC_FAILURE;
396          }
397          break;
398        }
399        case 0xd0: {
400          if (byte & 0x08)
401            return _URC_FAILURE;
402          _Unwind_VRS_Pop(context, _UVRSC_VFP, RegisterRange(8, byte & 0x7),
403                          _UVRSD_DOUBLE);
404          break;
405        }
406        default:
407          return _URC_FAILURE;
408      }
409    }
410  }
411  if (!wrotePC) {
412    uint32_t lr;
413    _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_LR, _UVRSD_UINT32, &lr);
414    _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_IP, _UVRSD_UINT32, &lr);
415  }
416  return _URC_CONTINUE_UNWIND;
417}
418
419extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr0(
420    _Unwind_State state,
421    _Unwind_Control_Block *ucbp,
422    _Unwind_Context *context) {
423  return unwindOneFrame(state, ucbp, context);
424}
425
426extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr1(
427    _Unwind_State state,
428    _Unwind_Control_Block *ucbp,
429    _Unwind_Context *context) {
430  return unwindOneFrame(state, ucbp, context);
431}
432
433extern "C" _Unwind_Reason_Code __aeabi_unwind_cpp_pr2(
434    _Unwind_State state,
435    _Unwind_Control_Block *ucbp,
436    _Unwind_Context *context) {
437  return unwindOneFrame(state, ucbp, context);
438}
439
440static _Unwind_Reason_Code
441unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception *exception_object) {
442  // EHABI #7.3 discusses preserving the VRS in a "temporary VRS" during
443  // phase 1 and then restoring it to the "primary VRS" for phase 2. The
444  // effect is phase 2 doesn't see any of the VRS manipulations from phase 1.
445  // In this implementation, the phases don't share the VRS backing store.
446  // Instead, they are passed the original |uc| and they create a new VRS
447  // from scratch thus achieving the same effect.
448  unw_init_local(cursor, uc);
449
450  // Walk each frame looking for a place to stop.
451  for (bool handlerNotFound = true; handlerNotFound;) {
452
453    // See if frame has code to run (has personality routine).
454    unw_proc_info_t frameInfo;
455    if (unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
456      _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): unw_get_proc_info "
457                                 "failed => _URC_FATAL_PHASE1_ERROR\n",
458                                 static_cast<void *>(exception_object));
459      return _URC_FATAL_PHASE1_ERROR;
460    }
461
462    // When tracing, print state information.
463    if (_LIBUNWIND_TRACING_UNWINDING) {
464      char functionBuf[512];
465      const char *functionName = functionBuf;
466      unw_word_t offset;
467      if ((unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
468                             &offset) != UNW_ESUCCESS) ||
469          (frameInfo.start_ip + offset > frameInfo.end_ip))
470        functionName = ".anonymous.";
471      unw_word_t pc;
472      unw_get_reg(cursor, UNW_REG_IP, &pc);
473      _LIBUNWIND_TRACE_UNWINDING(
474          "unwind_phase1(ex_ojb=%p): pc=0x%llX, start_ip=0x%llX, func=%s, "
475          "lsda=0x%llX, personality=0x%llX\n",
476          static_cast<void *>(exception_object), (long long)pc,
477          (long long)frameInfo.start_ip, functionName,
478          (long long)frameInfo.lsda, (long long)frameInfo.handler);
479    }
480
481    // If there is a personality routine, ask it if it will want to stop at
482    // this frame.
483    if (frameInfo.handler != 0) {
484      __personality_routine p =
485          (__personality_routine)(long)(frameInfo.handler);
486      _LIBUNWIND_TRACE_UNWINDING(
487          "unwind_phase1(ex_ojb=%p): calling personality function %p\n",
488          static_cast<void *>(exception_object),
489          reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(p)));
490      struct _Unwind_Context *context = (struct _Unwind_Context *)(cursor);
491      exception_object->pr_cache.fnstart = frameInfo.start_ip;
492      exception_object->pr_cache.ehtp =
493          (_Unwind_EHT_Header *)frameInfo.unwind_info;
494      exception_object->pr_cache.additional = frameInfo.flags;
495      _Unwind_Reason_Code personalityResult =
496          (*p)(_US_VIRTUAL_UNWIND_FRAME, exception_object, context);
497      _LIBUNWIND_TRACE_UNWINDING(
498          "unwind_phase1(ex_ojb=%p): personality result %d start_ip %x ehtp %p "
499          "additional %x\n",
500          static_cast<void *>(exception_object), personalityResult,
501          exception_object->pr_cache.fnstart,
502          static_cast<void *>(exception_object->pr_cache.ehtp),
503          exception_object->pr_cache.additional);
504      switch (personalityResult) {
505      case _URC_HANDLER_FOUND:
506        // found a catch clause or locals that need destructing in this frame
507        // stop search and remember stack pointer at the frame
508        handlerNotFound = false;
509        // p should have initialized barrier_cache. EHABI #7.3.5
510        _LIBUNWIND_TRACE_UNWINDING(
511            "unwind_phase1(ex_ojb=%p): _URC_HANDLER_FOUND \n",
512            static_cast<void *>(exception_object));
513        return _URC_NO_REASON;
514
515      case _URC_CONTINUE_UNWIND:
516        _LIBUNWIND_TRACE_UNWINDING(
517            "unwind_phase1(ex_ojb=%p): _URC_CONTINUE_UNWIND\n",
518            static_cast<void *>(exception_object));
519        // continue unwinding
520        break;
521
522      // EHABI #7.3.3
523      case _URC_FAILURE:
524        return _URC_FAILURE;
525
526      default:
527        // something went wrong
528        _LIBUNWIND_TRACE_UNWINDING(
529            "unwind_phase1(ex_ojb=%p): _URC_FATAL_PHASE1_ERROR\n",
530            static_cast<void *>(exception_object));
531        return _URC_FATAL_PHASE1_ERROR;
532      }
533    }
534  }
535  return _URC_NO_REASON;
536}
537
538static _Unwind_Reason_Code unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor,
539                                         _Unwind_Exception *exception_object,
540                                         bool resume) {
541  // See comment at the start of unwind_phase1 regarding VRS integrity.
542  unw_init_local(cursor, uc);
543
544  _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p)\n",
545                             static_cast<void *>(exception_object));
546  int frame_count = 0;
547
548  // Walk each frame until we reach where search phase said to stop.
549  while (true) {
550    // Ask libuwind to get next frame (skip over first which is
551    // _Unwind_RaiseException or _Unwind_Resume).
552    //
553    // Resume only ever makes sense for 1 frame.
554    _Unwind_State state =
555        resume ? _US_UNWIND_FRAME_RESUME : _US_UNWIND_FRAME_STARTING;
556    if (resume && frame_count == 1) {
557      // On a resume, first unwind the _Unwind_Resume() frame. The next frame
558      // is now the landing pad for the cleanup from a previous execution of
559      // phase2. To continue unwindingly correctly, replace VRS[15] with the
560      // IP of the frame that the previous run of phase2 installed the context
561      // for. After this, continue unwinding as if normal.
562      //
563      // See #7.4.6 for details.
564      unw_set_reg(cursor, UNW_REG_IP,
565                  exception_object->unwinder_cache.reserved2);
566      resume = false;
567    }
568
569    // Get info about this frame.
570    unw_word_t sp;
571    unw_proc_info_t frameInfo;
572    unw_get_reg(cursor, UNW_REG_SP, &sp);
573    if (unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
574      _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): unw_get_proc_info "
575                                 "failed => _URC_FATAL_PHASE2_ERROR\n",
576                                 static_cast<void *>(exception_object));
577      return _URC_FATAL_PHASE2_ERROR;
578    }
579
580    // When tracing, print state information.
581    if (_LIBUNWIND_TRACING_UNWINDING) {
582      char functionBuf[512];
583      const char *functionName = functionBuf;
584      unw_word_t offset;
585      if ((unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
586                             &offset) != UNW_ESUCCESS) ||
587          (frameInfo.start_ip + offset > frameInfo.end_ip))
588        functionName = ".anonymous.";
589      _LIBUNWIND_TRACE_UNWINDING(
590          "unwind_phase2(ex_ojb=%p): start_ip=0x%llX, func=%s, sp=0x%llX, "
591          "lsda=0x%llX, personality=0x%llX\n",
592          static_cast<void *>(exception_object), (long long)frameInfo.start_ip,
593          functionName, (long long)sp, (long long)frameInfo.lsda,
594          (long long)frameInfo.handler);
595    }
596
597    // If there is a personality routine, tell it we are unwinding.
598    if (frameInfo.handler != 0) {
599      __personality_routine p =
600          (__personality_routine)(long)(frameInfo.handler);
601      struct _Unwind_Context *context = (struct _Unwind_Context *)(cursor);
602      // EHABI #7.2
603      exception_object->pr_cache.fnstart = frameInfo.start_ip;
604      exception_object->pr_cache.ehtp =
605          (_Unwind_EHT_Header *)frameInfo.unwind_info;
606      exception_object->pr_cache.additional = frameInfo.flags;
607      _Unwind_Reason_Code personalityResult =
608          (*p)(state, exception_object, context);
609      switch (personalityResult) {
610      case _URC_CONTINUE_UNWIND:
611        // Continue unwinding
612        _LIBUNWIND_TRACE_UNWINDING(
613            "unwind_phase2(ex_ojb=%p): _URC_CONTINUE_UNWIND\n",
614            static_cast<void *>(exception_object));
615        // EHABI #7.2
616        if (sp == exception_object->barrier_cache.sp) {
617          // Phase 1 said we would stop at this frame, but we did not...
618          _LIBUNWIND_ABORT("during phase1 personality function said it would "
619                           "stop here, but now in phase2 it did not stop here");
620        }
621        break;
622      case _URC_INSTALL_CONTEXT:
623        _LIBUNWIND_TRACE_UNWINDING(
624            "unwind_phase2(ex_ojb=%p): _URC_INSTALL_CONTEXT\n",
625            static_cast<void *>(exception_object));
626        // Personality routine says to transfer control to landing pad.
627        // We may get control back if landing pad calls _Unwind_Resume().
628        if (_LIBUNWIND_TRACING_UNWINDING) {
629          unw_word_t pc;
630          unw_get_reg(cursor, UNW_REG_IP, &pc);
631          unw_get_reg(cursor, UNW_REG_SP, &sp);
632          _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): re-entering "
633                                     "user code with ip=0x%llX, sp=0x%llX\n",
634                                     static_cast<void *>(exception_object),
635                                     (long long)pc, (long long)sp);
636        }
637
638        {
639          // EHABI #7.4.1 says we need to preserve pc for when _Unwind_Resume
640          // is called back, to find this same frame.
641          unw_word_t pc;
642          unw_get_reg(cursor, UNW_REG_IP, &pc);
643          exception_object->unwinder_cache.reserved2 = (uint32_t)pc;
644        }
645        unw_resume(cursor);
646        // unw_resume() only returns if there was an error.
647        return _URC_FATAL_PHASE2_ERROR;
648
649      // # EHABI #7.4.3
650      case _URC_FAILURE:
651        abort();
652
653      default:
654        // Personality routine returned an unknown result code.
655        _LIBUNWIND_DEBUG_LOG("personality function returned unknown result %d",
656                      personalityResult);
657        return _URC_FATAL_PHASE2_ERROR;
658      }
659    }
660    frame_count++;
661  }
662
663  // Clean up phase did not resume at the frame that the search phase
664  // said it would...
665  return _URC_FATAL_PHASE2_ERROR;
666}
667
668/// Called by __cxa_throw.  Only returns if there is a fatal error.
669_LIBUNWIND_EXPORT _Unwind_Reason_Code
670_Unwind_RaiseException(_Unwind_Exception *exception_object) {
671  _LIBUNWIND_TRACE_API("_Unwind_RaiseException(ex_obj=%p)\n",
672                       static_cast<void *>(exception_object));
673  unw_context_t uc;
674  unw_cursor_t cursor;
675  unw_getcontext(&uc);
676
677  // This field for is for compatibility with GCC to say this isn't a forced
678  // unwind. EHABI #7.2
679  exception_object->unwinder_cache.reserved1 = 0;
680
681  // phase 1: the search phase
682  _Unwind_Reason_Code phase1 = unwind_phase1(&uc, &cursor, exception_object);
683  if (phase1 != _URC_NO_REASON)
684    return phase1;
685
686  // phase 2: the clean up phase
687  return unwind_phase2(&uc, &cursor, exception_object, false);
688}
689
690_LIBUNWIND_EXPORT void _Unwind_Complete(_Unwind_Exception* exception_object) {
691  // This is to be called when exception handling completes to give us a chance
692  // to perform any housekeeping. EHABI #7.2. But we have nothing to do here.
693  (void)exception_object;
694}
695
696/// When _Unwind_RaiseException() is in phase2, it hands control
697/// to the personality function at each frame.  The personality
698/// may force a jump to a landing pad in that function, the landing
699/// pad code may then call _Unwind_Resume() to continue with the
700/// unwinding.  Note: the call to _Unwind_Resume() is from compiler
701/// geneated user code.  All other _Unwind_* routines are called
702/// by the C++ runtime __cxa_* routines.
703///
704/// Note: re-throwing an exception (as opposed to continuing the unwind)
705/// is implemented by having the code call __cxa_rethrow() which
706/// in turn calls _Unwind_Resume_or_Rethrow().
707_LIBUNWIND_EXPORT void
708_Unwind_Resume(_Unwind_Exception *exception_object) {
709  _LIBUNWIND_TRACE_API("_Unwind_Resume(ex_obj=%p)\n",
710                       static_cast<void *>(exception_object));
711  unw_context_t uc;
712  unw_cursor_t cursor;
713  unw_getcontext(&uc);
714
715  // _Unwind_RaiseException on EHABI will always set the reserved1 field to 0,
716  // which is in the same position as private_1 below.
717  // TODO(ajwong): Who wronte the above? Why is it true?
718  unwind_phase2(&uc, &cursor, exception_object, true);
719
720  // Clients assume _Unwind_Resume() does not return, so all we can do is abort.
721  _LIBUNWIND_ABORT("_Unwind_Resume() can't return");
722}
723
724/// Called by personality handler during phase 2 to get LSDA for current frame.
725_LIBUNWIND_EXPORT uintptr_t
726_Unwind_GetLanguageSpecificData(struct _Unwind_Context *context) {
727  unw_cursor_t *cursor = (unw_cursor_t *)context;
728  unw_proc_info_t frameInfo;
729  uintptr_t result = 0;
730  if (unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
731    result = (uintptr_t)frameInfo.lsda;
732  _LIBUNWIND_TRACE_API(
733      "_Unwind_GetLanguageSpecificData(context=%p) => 0x%llx\n",
734      static_cast<void *>(context), (long long)result);
735  return result;
736}
737
738static uint64_t ValueAsBitPattern(_Unwind_VRS_DataRepresentation representation,
739                                  void* valuep) {
740  uint64_t value = 0;
741  switch (representation) {
742    case _UVRSD_UINT32:
743    case _UVRSD_FLOAT:
744      memcpy(&value, valuep, sizeof(uint32_t));
745      break;
746
747    case _UVRSD_VFPX:
748    case _UVRSD_UINT64:
749    case _UVRSD_DOUBLE:
750      memcpy(&value, valuep, sizeof(uint64_t));
751      break;
752  }
753  return value;
754}
755
756_Unwind_VRS_Result
757_Unwind_VRS_Set(_Unwind_Context *context, _Unwind_VRS_RegClass regclass,
758                uint32_t regno, _Unwind_VRS_DataRepresentation representation,
759                void *valuep) {
760  _LIBUNWIND_TRACE_API("_Unwind_VRS_Set(context=%p, regclass=%d, reg=%d, "
761                       "rep=%d, value=0x%llX)\n",
762                       static_cast<void *>(context), regclass, regno,
763                       representation,
764                       ValueAsBitPattern(representation, valuep));
765  unw_cursor_t *cursor = (unw_cursor_t *)context;
766  switch (regclass) {
767    case _UVRSC_CORE:
768      if (representation != _UVRSD_UINT32 || regno > 15)
769        return _UVRSR_FAILED;
770      return unw_set_reg(cursor, (unw_regnum_t)(UNW_ARM_R0 + regno),
771                         *(unw_word_t *)valuep) == UNW_ESUCCESS
772                 ? _UVRSR_OK
773                 : _UVRSR_FAILED;
774    case _UVRSC_WMMXC:
775      if (representation != _UVRSD_UINT32 || regno > 3)
776        return _UVRSR_FAILED;
777      return unw_set_reg(cursor, (unw_regnum_t)(UNW_ARM_WC0 + regno),
778                         *(unw_word_t *)valuep) == UNW_ESUCCESS
779                 ? _UVRSR_OK
780                 : _UVRSR_FAILED;
781    case _UVRSC_VFP:
782      if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
783        return _UVRSR_FAILED;
784      if (representation == _UVRSD_VFPX) {
785        // Can only touch d0-15 with FSTMFDX.
786        if (regno > 15)
787          return _UVRSR_FAILED;
788        unw_save_vfp_as_X(cursor);
789      } else {
790        if (regno > 31)
791          return _UVRSR_FAILED;
792      }
793      return unw_set_fpreg(cursor, (unw_regnum_t)(UNW_ARM_D0 + regno),
794                           *(unw_fpreg_t *)valuep) == UNW_ESUCCESS
795                 ? _UVRSR_OK
796                 : _UVRSR_FAILED;
797    case _UVRSC_WMMXD:
798      if (representation != _UVRSD_DOUBLE || regno > 31)
799        return _UVRSR_FAILED;
800      return unw_set_fpreg(cursor, (unw_regnum_t)(UNW_ARM_WR0 + regno),
801                           *(unw_fpreg_t *)valuep) == UNW_ESUCCESS
802                 ? _UVRSR_OK
803                 : _UVRSR_FAILED;
804  }
805  _LIBUNWIND_ABORT("unsupported register class");
806}
807
808static _Unwind_VRS_Result
809_Unwind_VRS_Get_Internal(_Unwind_Context *context,
810                         _Unwind_VRS_RegClass regclass, uint32_t regno,
811                         _Unwind_VRS_DataRepresentation representation,
812                         void *valuep) {
813  unw_cursor_t *cursor = (unw_cursor_t *)context;
814  switch (regclass) {
815    case _UVRSC_CORE:
816      if (representation != _UVRSD_UINT32 || regno > 15)
817        return _UVRSR_FAILED;
818      return unw_get_reg(cursor, (unw_regnum_t)(UNW_ARM_R0 + regno),
819                         (unw_word_t *)valuep) == UNW_ESUCCESS
820                 ? _UVRSR_OK
821                 : _UVRSR_FAILED;
822    case _UVRSC_WMMXC:
823      if (representation != _UVRSD_UINT32 || regno > 3)
824        return _UVRSR_FAILED;
825      return unw_get_reg(cursor, (unw_regnum_t)(UNW_ARM_WC0 + regno),
826                         (unw_word_t *)valuep) == UNW_ESUCCESS
827                 ? _UVRSR_OK
828                 : _UVRSR_FAILED;
829    case _UVRSC_VFP:
830      if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
831        return _UVRSR_FAILED;
832      if (representation == _UVRSD_VFPX) {
833        // Can only touch d0-15 with FSTMFDX.
834        if (regno > 15)
835          return _UVRSR_FAILED;
836        unw_save_vfp_as_X(cursor);
837      } else {
838        if (regno > 31)
839          return _UVRSR_FAILED;
840      }
841      return unw_get_fpreg(cursor, (unw_regnum_t)(UNW_ARM_D0 + regno),
842                           (unw_fpreg_t *)valuep) == UNW_ESUCCESS
843                 ? _UVRSR_OK
844                 : _UVRSR_FAILED;
845    case _UVRSC_WMMXD:
846      if (representation != _UVRSD_DOUBLE || regno > 31)
847        return _UVRSR_FAILED;
848      return unw_get_fpreg(cursor, (unw_regnum_t)(UNW_ARM_WR0 + regno),
849                           (unw_fpreg_t *)valuep) == UNW_ESUCCESS
850                 ? _UVRSR_OK
851                 : _UVRSR_FAILED;
852  }
853  _LIBUNWIND_ABORT("unsupported register class");
854}
855
856_Unwind_VRS_Result _Unwind_VRS_Get(
857    _Unwind_Context *context,
858    _Unwind_VRS_RegClass regclass,
859    uint32_t regno,
860    _Unwind_VRS_DataRepresentation representation,
861    void *valuep) {
862  _Unwind_VRS_Result result =
863      _Unwind_VRS_Get_Internal(context, regclass, regno, representation,
864                               valuep);
865  _LIBUNWIND_TRACE_API("_Unwind_VRS_Get(context=%p, regclass=%d, reg=%d, "
866                       "rep=%d, value=0x%llX, result = %d)\n",
867                       static_cast<void *>(context), regclass, regno,
868                       representation,
869                       ValueAsBitPattern(representation, valuep), result);
870  return result;
871}
872
873_Unwind_VRS_Result
874_Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass,
875                uint32_t discriminator,
876                _Unwind_VRS_DataRepresentation representation) {
877  _LIBUNWIND_TRACE_API("_Unwind_VRS_Pop(context=%p, regclass=%d, "
878                       "discriminator=%d, representation=%d)\n",
879                       static_cast<void *>(context), regclass, discriminator,
880                       representation);
881  switch (regclass) {
882    case _UVRSC_CORE:
883    case _UVRSC_WMMXC: {
884      if (representation != _UVRSD_UINT32)
885        return _UVRSR_FAILED;
886      // When popping SP from the stack, we don't want to override it from the
887      // computed new stack location. See EHABI #7.5.4 table 3.
888      bool poppedSP = false;
889      uint32_t* sp;
890      if (_Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP,
891                          _UVRSD_UINT32, &sp) != _UVRSR_OK) {
892        return _UVRSR_FAILED;
893      }
894      for (uint32_t i = 0; i < 16; ++i) {
895        if (!(discriminator & static_cast<uint32_t>(1 << i)))
896          continue;
897        uint32_t value = *sp++;
898        if (regclass == _UVRSC_CORE && i == 13)
899          poppedSP = true;
900        if (_Unwind_VRS_Set(context, regclass, i,
901                            _UVRSD_UINT32, &value) != _UVRSR_OK) {
902          return _UVRSR_FAILED;
903        }
904      }
905      if (!poppedSP) {
906        return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP,
907                               _UVRSD_UINT32, &sp);
908      }
909      return _UVRSR_OK;
910    }
911    case _UVRSC_VFP:
912    case _UVRSC_WMMXD: {
913      if (representation != _UVRSD_VFPX && representation != _UVRSD_DOUBLE)
914        return _UVRSR_FAILED;
915      uint32_t first = discriminator >> 16;
916      uint32_t count = discriminator & 0xffff;
917      uint32_t end = first+count;
918      uint32_t* sp;
919      if (_Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP,
920                          _UVRSD_UINT32, &sp) != _UVRSR_OK) {
921        return _UVRSR_FAILED;
922      }
923      // For _UVRSD_VFPX, we're assuming the data is stored in FSTMX "standard
924      // format 1", which is equivalent to FSTMD + a padding word.
925      for (uint32_t i = first; i < end; ++i) {
926        // SP is only 32-bit aligned so don't copy 64-bit at a time.
927        uint64_t value = *sp++;
928        value |= ((uint64_t)(*sp++)) << 32;
929        if (_Unwind_VRS_Set(context, regclass, i, representation, &value) !=
930            _UVRSR_OK)
931          return _UVRSR_FAILED;
932      }
933      if (representation == _UVRSD_VFPX)
934        ++sp;
935      return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32,
936                             &sp);
937    }
938  }
939  _LIBUNWIND_ABORT("unsupported register class");
940}
941
942/// Called by personality handler during phase 2 to find the start of the
943/// function.
944_LIBUNWIND_EXPORT uintptr_t
945_Unwind_GetRegionStart(struct _Unwind_Context *context) {
946  unw_cursor_t *cursor = (unw_cursor_t *)context;
947  unw_proc_info_t frameInfo;
948  uintptr_t result = 0;
949  if (unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
950    result = (uintptr_t)frameInfo.start_ip;
951  _LIBUNWIND_TRACE_API("_Unwind_GetRegionStart(context=%p) => 0x%llX\n",
952                       static_cast<void *>(context), (long long)result);
953  return result;
954}
955
956
957/// Called by personality handler during phase 2 if a foreign exception
958// is caught.
959_LIBUNWIND_EXPORT void
960_Unwind_DeleteException(_Unwind_Exception *exception_object) {
961  _LIBUNWIND_TRACE_API("_Unwind_DeleteException(ex_obj=%p)\n",
962                       static_cast<void *>(exception_object));
963  if (exception_object->exception_cleanup != NULL)
964    (*exception_object->exception_cleanup)(_URC_FOREIGN_EXCEPTION_CAUGHT,
965                                           exception_object);
966}
967
968extern "C" _LIBUNWIND_EXPORT _Unwind_Reason_Code
969__gnu_unwind_frame(_Unwind_Exception *exception_object,
970                   struct _Unwind_Context *context) {
971  unw_cursor_t *cursor = (unw_cursor_t *)context;
972  if (unw_step(cursor) != UNW_STEP_SUCCESS)
973    return _URC_FAILURE;
974  return _URC_OK;
975}
976
977#endif  // _LIBUNWIND_ARM_EHABI
978