1 //===------------------------- UnwindCursor.hpp ---------------------------===//
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 // C++ interface to lower levels of libunwind
10 //===----------------------------------------------------------------------===//
11 
12 #ifndef __UNWINDCURSOR_HPP__
13 #define __UNWINDCURSOR_HPP__
14 
15 #include <algorithm>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unwind.h>
20 
21 #ifdef _WIN32
22   #include <windows.h>
23   #include <ntverp.h>
24 #endif
25 #ifdef __APPLE__
26   #include <mach-o/dyld.h>
27 #endif
28 
29 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
30 // Provide a definition for the DISPATCHER_CONTEXT struct for old (Win7 and
31 // earlier) SDKs.
32 // MinGW-w64 has always provided this struct.
33   #if defined(_WIN32) && defined(_LIBUNWIND_TARGET_X86_64) && \
34       !defined(__MINGW32__) && VER_PRODUCTBUILD < 8000
35 struct _DISPATCHER_CONTEXT {
36   ULONG64 ControlPc;
37   ULONG64 ImageBase;
38   PRUNTIME_FUNCTION FunctionEntry;
39   ULONG64 EstablisherFrame;
40   ULONG64 TargetIp;
41   PCONTEXT ContextRecord;
42   PEXCEPTION_ROUTINE LanguageHandler;
43   PVOID HandlerData;
44   PUNWIND_HISTORY_TABLE HistoryTable;
45   ULONG ScopeIndex;
46   ULONG Fill0;
47 };
48   #endif
49 
50 struct UNWIND_INFO {
51   uint8_t Version : 3;
52   uint8_t Flags : 5;
53   uint8_t SizeOfProlog;
54   uint8_t CountOfCodes;
55   uint8_t FrameRegister : 4;
56   uint8_t FrameOffset : 4;
57   uint16_t UnwindCodes[2];
58 };
59 
60 extern "C" _Unwind_Reason_Code __libunwind_seh_personality(
61     int, _Unwind_Action, uint64_t, _Unwind_Exception *,
62     struct _Unwind_Context *);
63 
64 #endif
65 
66 #include "config.h"
67 
68 #include "AddressSpace.hpp"
69 #include "CompactUnwinder.hpp"
70 #include "config.h"
71 #include "DwarfInstructions.hpp"
72 #include "EHHeaderParser.hpp"
73 #include "libunwind.h"
74 #include "Registers.hpp"
75 #include "RWMutex.hpp"
76 #include "Unwind-EHABI.h"
77 
78 namespace libunwind {
79 
80 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
81 /// Cache of recently found FDEs.
82 template <typename A>
83 class _LIBUNWIND_HIDDEN DwarfFDECache {
84   typedef typename A::pint_t pint_t;
85 public:
86   static pint_t findFDE(pint_t mh, pint_t pc);
87   static void add(pint_t mh, pint_t ip_start, pint_t ip_end, pint_t fde);
88   static void removeAllIn(pint_t mh);
89   static void iterateCacheEntries(void (*func)(unw_word_t ip_start,
90                                                unw_word_t ip_end,
91                                                unw_word_t fde, unw_word_t mh));
92 
93 private:
94 
95   struct entry {
96     pint_t mh;
97     pint_t ip_start;
98     pint_t ip_end;
99     pint_t fde;
100   };
101 
102   // These fields are all static to avoid needing an initializer.
103   // There is only one instance of this class per process.
104   static RWMutex _lock;
105 #ifdef __APPLE__
106   static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
107   static bool _registeredForDyldUnloads;
108 #endif
109   // Can't use std::vector<> here because this code is below libc++.
110   static entry *_buffer;
111   static entry *_bufferUsed;
112   static entry *_bufferEnd;
113   static entry _initialBuffer[64];
114 };
115 
116 template <typename A>
117 typename DwarfFDECache<A>::entry *
118 DwarfFDECache<A>::_buffer = _initialBuffer;
119 
120 template <typename A>
121 typename DwarfFDECache<A>::entry *
122 DwarfFDECache<A>::_bufferUsed = _initialBuffer;
123 
124 template <typename A>
125 typename DwarfFDECache<A>::entry *
126 DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
127 
128 template <typename A>
129 typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
130 
131 template <typename A>
132 RWMutex DwarfFDECache<A>::_lock;
133 
134 #ifdef __APPLE__
135 template <typename A>
136 bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
137 #endif
138 
139 template <typename A>
140 typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
141   pint_t result = 0;
142   _LIBUNWIND_LOG_IF_FALSE(_lock.lock_shared());
143   for (entry *p = _buffer; p < _bufferUsed; ++p) {
144     if ((mh == p->mh) || (mh == 0)) {
145       if ((p->ip_start <= pc) && (pc < p->ip_end)) {
146         result = p->fde;
147         break;
148       }
149     }
150   }
151   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock_shared());
152   return result;
153 }
154 
155 template <typename A>
156 void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
157                            pint_t fde) {
158 #if !defined(_LIBUNWIND_NO_HEAP)
159   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
160   if (_bufferUsed >= _bufferEnd) {
161     size_t oldSize = (size_t)(_bufferEnd - _buffer);
162     size_t newSize = oldSize * 4;
163     // Can't use operator new (we are below it).
164     entry *newBuffer = (entry *)malloc(newSize * sizeof(entry));
165     memcpy(newBuffer, _buffer, oldSize * sizeof(entry));
166     if (_buffer != _initialBuffer)
167       free(_buffer);
168     _buffer = newBuffer;
169     _bufferUsed = &newBuffer[oldSize];
170     _bufferEnd = &newBuffer[newSize];
171   }
172   _bufferUsed->mh = mh;
173   _bufferUsed->ip_start = ip_start;
174   _bufferUsed->ip_end = ip_end;
175   _bufferUsed->fde = fde;
176   ++_bufferUsed;
177 #ifdef __APPLE__
178   if (!_registeredForDyldUnloads) {
179     _dyld_register_func_for_remove_image(&dyldUnloadHook);
180     _registeredForDyldUnloads = true;
181   }
182 #endif
183   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
184 #endif
185 }
186 
187 template <typename A>
188 void DwarfFDECache<A>::removeAllIn(pint_t mh) {
189   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
190   entry *d = _buffer;
191   for (const entry *s = _buffer; s < _bufferUsed; ++s) {
192     if (s->mh != mh) {
193       if (d != s)
194         *d = *s;
195       ++d;
196     }
197   }
198   _bufferUsed = d;
199   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
200 }
201 
202 #ifdef __APPLE__
203 template <typename A>
204 void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
205   removeAllIn((pint_t) mh);
206 }
207 #endif
208 
209 template <typename A>
210 void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
211     unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
212   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
213   for (entry *p = _buffer; p < _bufferUsed; ++p) {
214     (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
215   }
216   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
217 }
218 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
219 
220 
221 #define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
222 
223 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
224 template <typename A> class UnwindSectionHeader {
225 public:
226   UnwindSectionHeader(A &addressSpace, typename A::pint_t addr)
227       : _addressSpace(addressSpace), _addr(addr) {}
228 
229   uint32_t version() const {
230     return _addressSpace.get32(_addr +
231                                offsetof(unwind_info_section_header, version));
232   }
233   uint32_t commonEncodingsArraySectionOffset() const {
234     return _addressSpace.get32(_addr +
235                                offsetof(unwind_info_section_header,
236                                         commonEncodingsArraySectionOffset));
237   }
238   uint32_t commonEncodingsArrayCount() const {
239     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
240                                                 commonEncodingsArrayCount));
241   }
242   uint32_t personalityArraySectionOffset() const {
243     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
244                                                 personalityArraySectionOffset));
245   }
246   uint32_t personalityArrayCount() const {
247     return _addressSpace.get32(
248         _addr + offsetof(unwind_info_section_header, personalityArrayCount));
249   }
250   uint32_t indexSectionOffset() const {
251     return _addressSpace.get32(
252         _addr + offsetof(unwind_info_section_header, indexSectionOffset));
253   }
254   uint32_t indexCount() const {
255     return _addressSpace.get32(
256         _addr + offsetof(unwind_info_section_header, indexCount));
257   }
258 
259 private:
260   A                     &_addressSpace;
261   typename A::pint_t     _addr;
262 };
263 
264 template <typename A> class UnwindSectionIndexArray {
265 public:
266   UnwindSectionIndexArray(A &addressSpace, typename A::pint_t addr)
267       : _addressSpace(addressSpace), _addr(addr) {}
268 
269   uint32_t functionOffset(uint32_t index) const {
270     return _addressSpace.get32(
271         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
272                               functionOffset));
273   }
274   uint32_t secondLevelPagesSectionOffset(uint32_t index) const {
275     return _addressSpace.get32(
276         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
277                               secondLevelPagesSectionOffset));
278   }
279   uint32_t lsdaIndexArraySectionOffset(uint32_t index) const {
280     return _addressSpace.get32(
281         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
282                               lsdaIndexArraySectionOffset));
283   }
284 
285 private:
286   A                   &_addressSpace;
287   typename A::pint_t   _addr;
288 };
289 
290 template <typename A> class UnwindSectionRegularPageHeader {
291 public:
292   UnwindSectionRegularPageHeader(A &addressSpace, typename A::pint_t addr)
293       : _addressSpace(addressSpace), _addr(addr) {}
294 
295   uint32_t kind() const {
296     return _addressSpace.get32(
297         _addr + offsetof(unwind_info_regular_second_level_page_header, kind));
298   }
299   uint16_t entryPageOffset() const {
300     return _addressSpace.get16(
301         _addr + offsetof(unwind_info_regular_second_level_page_header,
302                          entryPageOffset));
303   }
304   uint16_t entryCount() const {
305     return _addressSpace.get16(
306         _addr +
307         offsetof(unwind_info_regular_second_level_page_header, entryCount));
308   }
309 
310 private:
311   A &_addressSpace;
312   typename A::pint_t _addr;
313 };
314 
315 template <typename A> class UnwindSectionRegularArray {
316 public:
317   UnwindSectionRegularArray(A &addressSpace, typename A::pint_t addr)
318       : _addressSpace(addressSpace), _addr(addr) {}
319 
320   uint32_t functionOffset(uint32_t index) const {
321     return _addressSpace.get32(
322         _addr + arrayoffsetof(unwind_info_regular_second_level_entry, index,
323                               functionOffset));
324   }
325   uint32_t encoding(uint32_t index) const {
326     return _addressSpace.get32(
327         _addr +
328         arrayoffsetof(unwind_info_regular_second_level_entry, index, encoding));
329   }
330 
331 private:
332   A &_addressSpace;
333   typename A::pint_t _addr;
334 };
335 
336 template <typename A> class UnwindSectionCompressedPageHeader {
337 public:
338   UnwindSectionCompressedPageHeader(A &addressSpace, typename A::pint_t addr)
339       : _addressSpace(addressSpace), _addr(addr) {}
340 
341   uint32_t kind() const {
342     return _addressSpace.get32(
343         _addr +
344         offsetof(unwind_info_compressed_second_level_page_header, kind));
345   }
346   uint16_t entryPageOffset() const {
347     return _addressSpace.get16(
348         _addr + offsetof(unwind_info_compressed_second_level_page_header,
349                          entryPageOffset));
350   }
351   uint16_t entryCount() const {
352     return _addressSpace.get16(
353         _addr +
354         offsetof(unwind_info_compressed_second_level_page_header, entryCount));
355   }
356   uint16_t encodingsPageOffset() const {
357     return _addressSpace.get16(
358         _addr + offsetof(unwind_info_compressed_second_level_page_header,
359                          encodingsPageOffset));
360   }
361   uint16_t encodingsCount() const {
362     return _addressSpace.get16(
363         _addr + offsetof(unwind_info_compressed_second_level_page_header,
364                          encodingsCount));
365   }
366 
367 private:
368   A &_addressSpace;
369   typename A::pint_t _addr;
370 };
371 
372 template <typename A> class UnwindSectionCompressedArray {
373 public:
374   UnwindSectionCompressedArray(A &addressSpace, typename A::pint_t addr)
375       : _addressSpace(addressSpace), _addr(addr) {}
376 
377   uint32_t functionOffset(uint32_t index) const {
378     return UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(
379         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
380   }
381   uint16_t encodingIndex(uint32_t index) const {
382     return UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(
383         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
384   }
385 
386 private:
387   A &_addressSpace;
388   typename A::pint_t _addr;
389 };
390 
391 template <typename A> class UnwindSectionLsdaArray {
392 public:
393   UnwindSectionLsdaArray(A &addressSpace, typename A::pint_t addr)
394       : _addressSpace(addressSpace), _addr(addr) {}
395 
396   uint32_t functionOffset(uint32_t index) const {
397     return _addressSpace.get32(
398         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
399                               index, functionOffset));
400   }
401   uint32_t lsdaOffset(uint32_t index) const {
402     return _addressSpace.get32(
403         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
404                               index, lsdaOffset));
405   }
406 
407 private:
408   A                   &_addressSpace;
409   typename A::pint_t   _addr;
410 };
411 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
412 
413 class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
414 public:
415   // NOTE: provide a class specific placement deallocation function (S5.3.4 p20)
416   // This avoids an unnecessary dependency to libc++abi.
417   void operator delete(void *, size_t) {}
418 
419   virtual ~AbstractUnwindCursor() {}
420   virtual bool validReg(int) { _LIBUNWIND_ABORT("validReg not implemented"); }
421   virtual unw_word_t getReg(int) { _LIBUNWIND_ABORT("getReg not implemented"); }
422   virtual void setReg(int, unw_word_t) {
423     _LIBUNWIND_ABORT("setReg not implemented");
424   }
425   virtual bool validFloatReg(int) {
426     _LIBUNWIND_ABORT("validFloatReg not implemented");
427   }
428   virtual unw_fpreg_t getFloatReg(int) {
429     _LIBUNWIND_ABORT("getFloatReg not implemented");
430   }
431   virtual void setFloatReg(int, unw_fpreg_t) {
432     _LIBUNWIND_ABORT("setFloatReg not implemented");
433   }
434   virtual int step() { _LIBUNWIND_ABORT("step not implemented"); }
435   virtual void getInfo(unw_proc_info_t *) {
436     _LIBUNWIND_ABORT("getInfo not implemented");
437   }
438   virtual void jumpto() { _LIBUNWIND_ABORT("jumpto not implemented"); }
439   virtual bool isSignalFrame() {
440     _LIBUNWIND_ABORT("isSignalFrame not implemented");
441   }
442   virtual bool getFunctionName(char *, size_t, unw_word_t *) {
443     _LIBUNWIND_ABORT("getFunctionName not implemented");
444   }
445   virtual void setInfoBasedOnIPRegister(bool = false) {
446     _LIBUNWIND_ABORT("setInfoBasedOnIPRegister not implemented");
447   }
448   virtual const char *getRegisterName(int) {
449     _LIBUNWIND_ABORT("getRegisterName not implemented");
450   }
451 #ifdef __arm__
452   virtual void saveVFPAsX() { _LIBUNWIND_ABORT("saveVFPAsX not implemented"); }
453 #endif
454 };
455 
456 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) && defined(_WIN32)
457 
458 /// \c UnwindCursor contains all state (including all register values) during
459 /// an unwind.  This is normally stack-allocated inside a unw_cursor_t.
460 template <typename A, typename R>
461 class UnwindCursor : public AbstractUnwindCursor {
462   typedef typename A::pint_t pint_t;
463 public:
464                       UnwindCursor(unw_context_t *context, A &as);
465                       UnwindCursor(CONTEXT *context, A &as);
466                       UnwindCursor(A &as, void *threadArg);
467   virtual             ~UnwindCursor() {}
468   virtual bool        validReg(int);
469   virtual unw_word_t  getReg(int);
470   virtual void        setReg(int, unw_word_t);
471   virtual bool        validFloatReg(int);
472   virtual unw_fpreg_t getFloatReg(int);
473   virtual void        setFloatReg(int, unw_fpreg_t);
474   virtual int         step();
475   virtual void        getInfo(unw_proc_info_t *);
476   virtual void        jumpto();
477   virtual bool        isSignalFrame();
478   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
479   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
480   virtual const char *getRegisterName(int num);
481 #ifdef __arm__
482   virtual void        saveVFPAsX();
483 #endif
484 
485   DISPATCHER_CONTEXT *getDispatcherContext() { return &_dispContext; }
486   void setDispatcherContext(DISPATCHER_CONTEXT *disp) { _dispContext = *disp; }
487 
488 private:
489 
490   pint_t getLastPC() const { return _dispContext.ControlPc; }
491   void setLastPC(pint_t pc) { _dispContext.ControlPc = pc; }
492   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
493     _dispContext.FunctionEntry = RtlLookupFunctionEntry(pc,
494                                                         &_dispContext.ImageBase,
495                                                         _dispContext.HistoryTable);
496     *base = _dispContext.ImageBase;
497     return _dispContext.FunctionEntry;
498   }
499   bool getInfoFromSEH(pint_t pc);
500   int stepWithSEHData() {
501     _dispContext.LanguageHandler = RtlVirtualUnwind(UNW_FLAG_UHANDLER,
502                                                     _dispContext.ImageBase,
503                                                     _dispContext.ControlPc,
504                                                     _dispContext.FunctionEntry,
505                                                     _dispContext.ContextRecord,
506                                                     &_dispContext.HandlerData,
507                                                     &_dispContext.EstablisherFrame,
508                                                     NULL);
509     // Update some fields of the unwind info now, since we have them.
510     _info.lsda = reinterpret_cast<unw_word_t>(_dispContext.HandlerData);
511     if (_dispContext.LanguageHandler) {
512       _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
513     } else
514       _info.handler = 0;
515     return UNW_STEP_SUCCESS;
516   }
517 
518   A                   &_addressSpace;
519   unw_proc_info_t      _info;
520   DISPATCHER_CONTEXT   _dispContext;
521   CONTEXT              _msContext;
522   UNWIND_HISTORY_TABLE _histTable;
523   bool                 _unwindInfoMissing;
524 };
525 
526 
527 template <typename A, typename R>
528 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
529     : _addressSpace(as), _unwindInfoMissing(false) {
530   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
531                 "UnwindCursor<> does not fit in unw_cursor_t");
532   memset(&_info, 0, sizeof(_info));
533   memset(&_histTable, 0, sizeof(_histTable));
534   _dispContext.ContextRecord = &_msContext;
535   _dispContext.HistoryTable = &_histTable;
536   // Initialize MS context from ours.
537   R r(context);
538   _msContext.ContextFlags = CONTEXT_CONTROL|CONTEXT_INTEGER|CONTEXT_FLOATING_POINT;
539 #if defined(_LIBUNWIND_TARGET_X86_64)
540   _msContext.Rax = r.getRegister(UNW_X86_64_RAX);
541   _msContext.Rcx = r.getRegister(UNW_X86_64_RCX);
542   _msContext.Rdx = r.getRegister(UNW_X86_64_RDX);
543   _msContext.Rbx = r.getRegister(UNW_X86_64_RBX);
544   _msContext.Rsp = r.getRegister(UNW_X86_64_RSP);
545   _msContext.Rbp = r.getRegister(UNW_X86_64_RBP);
546   _msContext.Rsi = r.getRegister(UNW_X86_64_RSI);
547   _msContext.Rdi = r.getRegister(UNW_X86_64_RDI);
548   _msContext.R8 = r.getRegister(UNW_X86_64_R8);
549   _msContext.R9 = r.getRegister(UNW_X86_64_R9);
550   _msContext.R10 = r.getRegister(UNW_X86_64_R10);
551   _msContext.R11 = r.getRegister(UNW_X86_64_R11);
552   _msContext.R12 = r.getRegister(UNW_X86_64_R12);
553   _msContext.R13 = r.getRegister(UNW_X86_64_R13);
554   _msContext.R14 = r.getRegister(UNW_X86_64_R14);
555   _msContext.R15 = r.getRegister(UNW_X86_64_R15);
556   _msContext.Rip = r.getRegister(UNW_REG_IP);
557   union {
558     v128 v;
559     M128A m;
560   } t;
561   t.v = r.getVectorRegister(UNW_X86_64_XMM0);
562   _msContext.Xmm0 = t.m;
563   t.v = r.getVectorRegister(UNW_X86_64_XMM1);
564   _msContext.Xmm1 = t.m;
565   t.v = r.getVectorRegister(UNW_X86_64_XMM2);
566   _msContext.Xmm2 = t.m;
567   t.v = r.getVectorRegister(UNW_X86_64_XMM3);
568   _msContext.Xmm3 = t.m;
569   t.v = r.getVectorRegister(UNW_X86_64_XMM4);
570   _msContext.Xmm4 = t.m;
571   t.v = r.getVectorRegister(UNW_X86_64_XMM5);
572   _msContext.Xmm5 = t.m;
573   t.v = r.getVectorRegister(UNW_X86_64_XMM6);
574   _msContext.Xmm6 = t.m;
575   t.v = r.getVectorRegister(UNW_X86_64_XMM7);
576   _msContext.Xmm7 = t.m;
577   t.v = r.getVectorRegister(UNW_X86_64_XMM8);
578   _msContext.Xmm8 = t.m;
579   t.v = r.getVectorRegister(UNW_X86_64_XMM9);
580   _msContext.Xmm9 = t.m;
581   t.v = r.getVectorRegister(UNW_X86_64_XMM10);
582   _msContext.Xmm10 = t.m;
583   t.v = r.getVectorRegister(UNW_X86_64_XMM11);
584   _msContext.Xmm11 = t.m;
585   t.v = r.getVectorRegister(UNW_X86_64_XMM12);
586   _msContext.Xmm12 = t.m;
587   t.v = r.getVectorRegister(UNW_X86_64_XMM13);
588   _msContext.Xmm13 = t.m;
589   t.v = r.getVectorRegister(UNW_X86_64_XMM14);
590   _msContext.Xmm14 = t.m;
591   t.v = r.getVectorRegister(UNW_X86_64_XMM15);
592   _msContext.Xmm15 = t.m;
593 #elif defined(_LIBUNWIND_TARGET_ARM)
594   _msContext.R0 = r.getRegister(UNW_ARM_R0);
595   _msContext.R1 = r.getRegister(UNW_ARM_R1);
596   _msContext.R2 = r.getRegister(UNW_ARM_R2);
597   _msContext.R3 = r.getRegister(UNW_ARM_R3);
598   _msContext.R4 = r.getRegister(UNW_ARM_R4);
599   _msContext.R5 = r.getRegister(UNW_ARM_R5);
600   _msContext.R6 = r.getRegister(UNW_ARM_R6);
601   _msContext.R7 = r.getRegister(UNW_ARM_R7);
602   _msContext.R8 = r.getRegister(UNW_ARM_R8);
603   _msContext.R9 = r.getRegister(UNW_ARM_R9);
604   _msContext.R10 = r.getRegister(UNW_ARM_R10);
605   _msContext.R11 = r.getRegister(UNW_ARM_R11);
606   _msContext.R12 = r.getRegister(UNW_ARM_R12);
607   _msContext.Sp = r.getRegister(UNW_ARM_SP);
608   _msContext.Lr = r.getRegister(UNW_ARM_LR);
609   _msContext.Pc = r.getRegister(UNW_ARM_IP);
610   for (int i = UNW_ARM_D0; i <= UNW_ARM_D31; ++i) {
611     union {
612       uint64_t w;
613       double d;
614     } d;
615     d.d = r.getFloatRegister(i);
616     _msContext.D[i - UNW_ARM_D0] = d.w;
617   }
618 #endif
619 }
620 
621 template <typename A, typename R>
622 UnwindCursor<A, R>::UnwindCursor(CONTEXT *context, A &as)
623     : _addressSpace(as), _unwindInfoMissing(false) {
624   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
625                 "UnwindCursor<> does not fit in unw_cursor_t");
626   memset(&_info, 0, sizeof(_info));
627   memset(&_histTable, 0, sizeof(_histTable));
628   _dispContext.ContextRecord = &_msContext;
629   _dispContext.HistoryTable = &_histTable;
630   _msContext = *context;
631 }
632 
633 
634 template <typename A, typename R>
635 bool UnwindCursor<A, R>::validReg(int regNum) {
636   if (regNum == UNW_REG_IP || regNum == UNW_REG_SP) return true;
637 #if defined(_LIBUNWIND_TARGET_X86_64)
638   if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
639 #elif defined(_LIBUNWIND_TARGET_ARM)
640   if (regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) return true;
641 #endif
642   return false;
643 }
644 
645 template <typename A, typename R>
646 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
647   switch (regNum) {
648 #if defined(_LIBUNWIND_TARGET_X86_64)
649   case UNW_REG_IP: return _msContext.Rip;
650   case UNW_X86_64_RAX: return _msContext.Rax;
651   case UNW_X86_64_RDX: return _msContext.Rdx;
652   case UNW_X86_64_RCX: return _msContext.Rcx;
653   case UNW_X86_64_RBX: return _msContext.Rbx;
654   case UNW_REG_SP:
655   case UNW_X86_64_RSP: return _msContext.Rsp;
656   case UNW_X86_64_RBP: return _msContext.Rbp;
657   case UNW_X86_64_RSI: return _msContext.Rsi;
658   case UNW_X86_64_RDI: return _msContext.Rdi;
659   case UNW_X86_64_R8: return _msContext.R8;
660   case UNW_X86_64_R9: return _msContext.R9;
661   case UNW_X86_64_R10: return _msContext.R10;
662   case UNW_X86_64_R11: return _msContext.R11;
663   case UNW_X86_64_R12: return _msContext.R12;
664   case UNW_X86_64_R13: return _msContext.R13;
665   case UNW_X86_64_R14: return _msContext.R14;
666   case UNW_X86_64_R15: return _msContext.R15;
667 #elif defined(_LIBUNWIND_TARGET_ARM)
668   case UNW_ARM_R0: return _msContext.R0;
669   case UNW_ARM_R1: return _msContext.R1;
670   case UNW_ARM_R2: return _msContext.R2;
671   case UNW_ARM_R3: return _msContext.R3;
672   case UNW_ARM_R4: return _msContext.R4;
673   case UNW_ARM_R5: return _msContext.R5;
674   case UNW_ARM_R6: return _msContext.R6;
675   case UNW_ARM_R7: return _msContext.R7;
676   case UNW_ARM_R8: return _msContext.R8;
677   case UNW_ARM_R9: return _msContext.R9;
678   case UNW_ARM_R10: return _msContext.R10;
679   case UNW_ARM_R11: return _msContext.R11;
680   case UNW_ARM_R12: return _msContext.R12;
681   case UNW_REG_SP:
682   case UNW_ARM_SP: return _msContext.Sp;
683   case UNW_ARM_LR: return _msContext.Lr;
684   case UNW_REG_IP:
685   case UNW_ARM_IP: return _msContext.Pc;
686 #endif
687   }
688   _LIBUNWIND_ABORT("unsupported register");
689 }
690 
691 template <typename A, typename R>
692 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
693   switch (regNum) {
694 #if defined(_LIBUNWIND_TARGET_X86_64)
695   case UNW_REG_IP: _msContext.Rip = value; break;
696   case UNW_X86_64_RAX: _msContext.Rax = value; break;
697   case UNW_X86_64_RDX: _msContext.Rdx = value; break;
698   case UNW_X86_64_RCX: _msContext.Rcx = value; break;
699   case UNW_X86_64_RBX: _msContext.Rbx = value; break;
700   case UNW_REG_SP:
701   case UNW_X86_64_RSP: _msContext.Rsp = value; break;
702   case UNW_X86_64_RBP: _msContext.Rbp = value; break;
703   case UNW_X86_64_RSI: _msContext.Rsi = value; break;
704   case UNW_X86_64_RDI: _msContext.Rdi = value; break;
705   case UNW_X86_64_R8: _msContext.R8 = value; break;
706   case UNW_X86_64_R9: _msContext.R9 = value; break;
707   case UNW_X86_64_R10: _msContext.R10 = value; break;
708   case UNW_X86_64_R11: _msContext.R11 = value; break;
709   case UNW_X86_64_R12: _msContext.R12 = value; break;
710   case UNW_X86_64_R13: _msContext.R13 = value; break;
711   case UNW_X86_64_R14: _msContext.R14 = value; break;
712   case UNW_X86_64_R15: _msContext.R15 = value; break;
713 #elif defined(_LIBUNWIND_TARGET_ARM)
714   case UNW_ARM_R0: _msContext.R0 = value; break;
715   case UNW_ARM_R1: _msContext.R1 = value; break;
716   case UNW_ARM_R2: _msContext.R2 = value; break;
717   case UNW_ARM_R3: _msContext.R3 = value; break;
718   case UNW_ARM_R4: _msContext.R4 = value; break;
719   case UNW_ARM_R5: _msContext.R5 = value; break;
720   case UNW_ARM_R6: _msContext.R6 = value; break;
721   case UNW_ARM_R7: _msContext.R7 = value; break;
722   case UNW_ARM_R8: _msContext.R8 = value; break;
723   case UNW_ARM_R9: _msContext.R9 = value; break;
724   case UNW_ARM_R10: _msContext.R10 = value; break;
725   case UNW_ARM_R11: _msContext.R11 = value; break;
726   case UNW_ARM_R12: _msContext.R12 = value; break;
727   case UNW_REG_SP:
728   case UNW_ARM_SP: _msContext.Sp = value; break;
729   case UNW_ARM_LR: _msContext.Lr = value; break;
730   case UNW_REG_IP:
731   case UNW_ARM_IP: _msContext.Pc = value; break;
732 #endif
733   default:
734     _LIBUNWIND_ABORT("unsupported register");
735   }
736 }
737 
738 template <typename A, typename R>
739 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
740 #if defined(_LIBUNWIND_TARGET_ARM)
741   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) return true;
742   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) return true;
743 #endif
744   return false;
745 }
746 
747 template <typename A, typename R>
748 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
749 #if defined(_LIBUNWIND_TARGET_ARM)
750   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
751     union {
752       uint32_t w;
753       float f;
754     } d;
755     d.w = _msContext.S[regNum - UNW_ARM_S0];
756     return d.f;
757   }
758   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
759     union {
760       uint64_t w;
761       double d;
762     } d;
763     d.w = _msContext.D[regNum - UNW_ARM_D0];
764     return d.d;
765   }
766   _LIBUNWIND_ABORT("unsupported float register");
767 #else
768   _LIBUNWIND_ABORT("float registers unimplemented");
769 #endif
770 }
771 
772 template <typename A, typename R>
773 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
774 #if defined(_LIBUNWIND_TARGET_ARM)
775   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
776     union {
777       uint32_t w;
778       float f;
779     } d;
780     d.f = value;
781     _msContext.S[regNum - UNW_ARM_S0] = d.w;
782   }
783   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
784     union {
785       uint64_t w;
786       double d;
787     } d;
788     d.d = value;
789     _msContext.D[regNum - UNW_ARM_D0] = d.w;
790   }
791   _LIBUNWIND_ABORT("unsupported float register");
792 #else
793   _LIBUNWIND_ABORT("float registers unimplemented");
794 #endif
795 }
796 
797 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
798   RtlRestoreContext(&_msContext, nullptr);
799 }
800 
801 #ifdef __arm__
802 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {}
803 #endif
804 
805 template <typename A, typename R>
806 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
807   switch (regNum) {
808 #if defined(_LIBUNWIND_TARGET_X86_64)
809   case UNW_REG_IP: return "rip";
810   case UNW_X86_64_RAX: return "rax";
811   case UNW_X86_64_RDX: return "rdx";
812   case UNW_X86_64_RCX: return "rcx";
813   case UNW_X86_64_RBX: return "rbx";
814   case UNW_REG_SP:
815   case UNW_X86_64_RSP: return "rsp";
816   case UNW_X86_64_RBP: return "rbp";
817   case UNW_X86_64_RSI: return "rsi";
818   case UNW_X86_64_RDI: return "rdi";
819   case UNW_X86_64_R8: return "r8";
820   case UNW_X86_64_R9: return "r9";
821   case UNW_X86_64_R10: return "r10";
822   case UNW_X86_64_R11: return "r11";
823   case UNW_X86_64_R12: return "r12";
824   case UNW_X86_64_R13: return "r13";
825   case UNW_X86_64_R14: return "r14";
826   case UNW_X86_64_R15: return "r15";
827 #elif defined(_LIBUNWIND_TARGET_ARM)
828   case UNW_ARM_R0: return "r0";
829   case UNW_ARM_R1: return "r1";
830   case UNW_ARM_R2: return "r2";
831   case UNW_ARM_R3: return "r3";
832   case UNW_ARM_R4: return "r4";
833   case UNW_ARM_R5: return "r5";
834   case UNW_ARM_R6: return "r6";
835   case UNW_ARM_R7: return "r7";
836   case UNW_ARM_R8: return "r8";
837   case UNW_ARM_R9: return "r9";
838   case UNW_ARM_R10: return "r10";
839   case UNW_ARM_R11: return "r11";
840   case UNW_ARM_R12: return "r12";
841   case UNW_REG_SP:
842   case UNW_ARM_SP: return "sp";
843   case UNW_ARM_LR: return "lr";
844   case UNW_REG_IP:
845   case UNW_ARM_IP: return "pc";
846   case UNW_ARM_S0: return "s0";
847   case UNW_ARM_S1: return "s1";
848   case UNW_ARM_S2: return "s2";
849   case UNW_ARM_S3: return "s3";
850   case UNW_ARM_S4: return "s4";
851   case UNW_ARM_S5: return "s5";
852   case UNW_ARM_S6: return "s6";
853   case UNW_ARM_S7: return "s7";
854   case UNW_ARM_S8: return "s8";
855   case UNW_ARM_S9: return "s9";
856   case UNW_ARM_S10: return "s10";
857   case UNW_ARM_S11: return "s11";
858   case UNW_ARM_S12: return "s12";
859   case UNW_ARM_S13: return "s13";
860   case UNW_ARM_S14: return "s14";
861   case UNW_ARM_S15: return "s15";
862   case UNW_ARM_S16: return "s16";
863   case UNW_ARM_S17: return "s17";
864   case UNW_ARM_S18: return "s18";
865   case UNW_ARM_S19: return "s19";
866   case UNW_ARM_S20: return "s20";
867   case UNW_ARM_S21: return "s21";
868   case UNW_ARM_S22: return "s22";
869   case UNW_ARM_S23: return "s23";
870   case UNW_ARM_S24: return "s24";
871   case UNW_ARM_S25: return "s25";
872   case UNW_ARM_S26: return "s26";
873   case UNW_ARM_S27: return "s27";
874   case UNW_ARM_S28: return "s28";
875   case UNW_ARM_S29: return "s29";
876   case UNW_ARM_S30: return "s30";
877   case UNW_ARM_S31: return "s31";
878   case UNW_ARM_D0: return "d0";
879   case UNW_ARM_D1: return "d1";
880   case UNW_ARM_D2: return "d2";
881   case UNW_ARM_D3: return "d3";
882   case UNW_ARM_D4: return "d4";
883   case UNW_ARM_D5: return "d5";
884   case UNW_ARM_D6: return "d6";
885   case UNW_ARM_D7: return "d7";
886   case UNW_ARM_D8: return "d8";
887   case UNW_ARM_D9: return "d9";
888   case UNW_ARM_D10: return "d10";
889   case UNW_ARM_D11: return "d11";
890   case UNW_ARM_D12: return "d12";
891   case UNW_ARM_D13: return "d13";
892   case UNW_ARM_D14: return "d14";
893   case UNW_ARM_D15: return "d15";
894   case UNW_ARM_D16: return "d16";
895   case UNW_ARM_D17: return "d17";
896   case UNW_ARM_D18: return "d18";
897   case UNW_ARM_D19: return "d19";
898   case UNW_ARM_D20: return "d20";
899   case UNW_ARM_D21: return "d21";
900   case UNW_ARM_D22: return "d22";
901   case UNW_ARM_D23: return "d23";
902   case UNW_ARM_D24: return "d24";
903   case UNW_ARM_D25: return "d25";
904   case UNW_ARM_D26: return "d26";
905   case UNW_ARM_D27: return "d27";
906   case UNW_ARM_D28: return "d28";
907   case UNW_ARM_D29: return "d29";
908   case UNW_ARM_D30: return "d30";
909   case UNW_ARM_D31: return "d31";
910 #endif
911   default:
912     _LIBUNWIND_ABORT("unsupported register");
913   }
914 }
915 
916 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
917   return false;
918 }
919 
920 #else  // !defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) || !defined(_WIN32)
921 
922 /// UnwindCursor contains all state (including all register values) during
923 /// an unwind.  This is normally stack allocated inside a unw_cursor_t.
924 template <typename A, typename R>
925 class UnwindCursor : public AbstractUnwindCursor{
926   typedef typename A::pint_t pint_t;
927 public:
928                       UnwindCursor(unw_context_t *context, A &as);
929                       UnwindCursor(A &as, void *threadArg);
930   virtual             ~UnwindCursor() {}
931   virtual bool        validReg(int);
932   virtual unw_word_t  getReg(int);
933   virtual void        setReg(int, unw_word_t);
934   virtual bool        validFloatReg(int);
935   virtual unw_fpreg_t getFloatReg(int);
936   virtual void        setFloatReg(int, unw_fpreg_t);
937   virtual int         step();
938   virtual void        getInfo(unw_proc_info_t *);
939   virtual void        jumpto();
940   virtual bool        isSignalFrame();
941   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
942   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
943   virtual const char *getRegisterName(int num);
944 #ifdef __arm__
945   virtual void        saveVFPAsX();
946 #endif
947 
948 private:
949 
950 #if defined(_LIBUNWIND_ARM_EHABI)
951   bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
952 
953   int stepWithEHABI() {
954     size_t len = 0;
955     size_t off = 0;
956     // FIXME: Calling decode_eht_entry() here is violating the libunwind
957     // abstraction layer.
958     const uint32_t *ehtp =
959         decode_eht_entry(reinterpret_cast<const uint32_t *>(_info.unwind_info),
960                          &off, &len);
961     if (_Unwind_VRS_Interpret((_Unwind_Context *)this, ehtp, off, len) !=
962             _URC_CONTINUE_UNWIND)
963       return UNW_STEP_END;
964     return UNW_STEP_SUCCESS;
965   }
966 #endif
967 
968 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
969   bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
970                                             uint32_t fdeSectionOffsetHint=0);
971   int stepWithDwarfFDE() {
972     return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
973                                               (pint_t)this->getReg(UNW_REG_IP),
974                                               (pint_t)_info.unwind_info,
975                                               _registers);
976   }
977 #endif
978 
979 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
980   bool getInfoFromCompactEncodingSection(pint_t pc,
981                                             const UnwindInfoSections &sects);
982   int stepWithCompactEncoding() {
983   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
984     if ( compactSaysUseDwarf() )
985       return stepWithDwarfFDE();
986   #endif
987     R dummy;
988     return stepWithCompactEncoding(dummy);
989   }
990 
991 #if defined(_LIBUNWIND_TARGET_X86_64)
992   int stepWithCompactEncoding(Registers_x86_64 &) {
993     return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
994         _info.format, _info.start_ip, _addressSpace, _registers);
995   }
996 #endif
997 
998 #if defined(_LIBUNWIND_TARGET_I386)
999   int stepWithCompactEncoding(Registers_x86 &) {
1000     return CompactUnwinder_x86<A>::stepWithCompactEncoding(
1001         _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
1002   }
1003 #endif
1004 
1005 #if defined(_LIBUNWIND_TARGET_PPC)
1006   int stepWithCompactEncoding(Registers_ppc &) {
1007     return UNW_EINVAL;
1008   }
1009 #endif
1010 
1011 #if defined(_LIBUNWIND_TARGET_PPC64)
1012   int stepWithCompactEncoding(Registers_ppc64 &) {
1013     return UNW_EINVAL;
1014   }
1015 #endif
1016 
1017 
1018 #if defined(_LIBUNWIND_TARGET_AARCH64)
1019   int stepWithCompactEncoding(Registers_arm64 &) {
1020     return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
1021         _info.format, _info.start_ip, _addressSpace, _registers);
1022   }
1023 #endif
1024 
1025 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1026   int stepWithCompactEncoding(Registers_mips_o32 &) {
1027     return UNW_EINVAL;
1028   }
1029 #endif
1030 
1031 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1032   int stepWithCompactEncoding(Registers_mips_newabi &) {
1033     return UNW_EINVAL;
1034   }
1035 #endif
1036 
1037   bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1038     R dummy;
1039     return compactSaysUseDwarf(dummy, offset);
1040   }
1041 
1042 #if defined(_LIBUNWIND_TARGET_X86_64)
1043   bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1044     if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1045       if (offset)
1046         *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1047       return true;
1048     }
1049     return false;
1050   }
1051 #endif
1052 
1053 #if defined(_LIBUNWIND_TARGET_I386)
1054   bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1055     if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1056       if (offset)
1057         *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1058       return true;
1059     }
1060     return false;
1061   }
1062 #endif
1063 
1064 #if defined(_LIBUNWIND_TARGET_PPC)
1065   bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1066     return true;
1067   }
1068 #endif
1069 
1070 #if defined(_LIBUNWIND_TARGET_PPC64)
1071   bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1072     return true;
1073   }
1074 #endif
1075 
1076 #if defined(_LIBUNWIND_TARGET_AARCH64)
1077   bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1078     if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1079       if (offset)
1080         *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1081       return true;
1082     }
1083     return false;
1084   }
1085 #endif
1086 
1087 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1088   bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1089     return true;
1090   }
1091 #endif
1092 
1093 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1094   bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
1095     return true;
1096   }
1097 #endif
1098 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1099 
1100 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1101   compact_unwind_encoding_t dwarfEncoding() const {
1102     R dummy;
1103     return dwarfEncoding(dummy);
1104   }
1105 
1106 #if defined(_LIBUNWIND_TARGET_X86_64)
1107   compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1108     return UNWIND_X86_64_MODE_DWARF;
1109   }
1110 #endif
1111 
1112 #if defined(_LIBUNWIND_TARGET_I386)
1113   compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1114     return UNWIND_X86_MODE_DWARF;
1115   }
1116 #endif
1117 
1118 #if defined(_LIBUNWIND_TARGET_PPC)
1119   compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1120     return 0;
1121   }
1122 #endif
1123 
1124 #if defined(_LIBUNWIND_TARGET_PPC64)
1125   compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1126     return 0;
1127   }
1128 #endif
1129 
1130 #if defined(_LIBUNWIND_TARGET_AARCH64)
1131   compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1132     return UNWIND_ARM64_MODE_DWARF;
1133   }
1134 #endif
1135 
1136 #if defined(_LIBUNWIND_TARGET_ARM)
1137   compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1138     return 0;
1139   }
1140 #endif
1141 
1142 #if defined (_LIBUNWIND_TARGET_OR1K)
1143   compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1144     return 0;
1145   }
1146 #endif
1147 
1148 #if defined (_LIBUNWIND_TARGET_MIPS_O32)
1149   compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1150     return 0;
1151   }
1152 #endif
1153 
1154 #if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1155   compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
1156     return 0;
1157   }
1158 #endif
1159 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1160 
1161 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1162   // For runtime environments using SEH unwind data without Windows runtime
1163   // support.
1164   pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1165   void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1166   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1167     /* FIXME: Implement */
1168     *base = 0;
1169     return nullptr;
1170   }
1171   bool getInfoFromSEH(pint_t pc);
1172   int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1173 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1174 
1175 
1176   A               &_addressSpace;
1177   R                _registers;
1178   unw_proc_info_t  _info;
1179   bool             _unwindInfoMissing;
1180   bool             _isSignalFrame;
1181 };
1182 
1183 
1184 template <typename A, typename R>
1185 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1186     : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1187       _isSignalFrame(false) {
1188   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
1189                 "UnwindCursor<> does not fit in unw_cursor_t");
1190   memset(&_info, 0, sizeof(_info));
1191 }
1192 
1193 template <typename A, typename R>
1194 UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1195     : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1196   memset(&_info, 0, sizeof(_info));
1197   // FIXME
1198   // fill in _registers from thread arg
1199 }
1200 
1201 
1202 template <typename A, typename R>
1203 bool UnwindCursor<A, R>::validReg(int regNum) {
1204   return _registers.validRegister(regNum);
1205 }
1206 
1207 template <typename A, typename R>
1208 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1209   return _registers.getRegister(regNum);
1210 }
1211 
1212 template <typename A, typename R>
1213 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1214   _registers.setRegister(regNum, (typename A::pint_t)value);
1215 }
1216 
1217 template <typename A, typename R>
1218 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1219   return _registers.validFloatRegister(regNum);
1220 }
1221 
1222 template <typename A, typename R>
1223 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1224   return _registers.getFloatRegister(regNum);
1225 }
1226 
1227 template <typename A, typename R>
1228 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1229   _registers.setFloatRegister(regNum, value);
1230 }
1231 
1232 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1233   _registers.jumpto();
1234 }
1235 
1236 #ifdef __arm__
1237 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1238   _registers.saveVFPAsX();
1239 }
1240 #endif
1241 
1242 template <typename A, typename R>
1243 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1244   return _registers.getRegisterName(regNum);
1245 }
1246 
1247 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1248   return _isSignalFrame;
1249 }
1250 
1251 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1252 
1253 #if defined(_LIBUNWIND_ARM_EHABI)
1254 struct EHABIIndexEntry {
1255   uint32_t functionOffset;
1256   uint32_t data;
1257 };
1258 
1259 template<typename A>
1260 struct EHABISectionIterator {
1261   typedef EHABISectionIterator _Self;
1262 
1263   typedef std::random_access_iterator_tag iterator_category;
1264   typedef typename A::pint_t value_type;
1265   typedef typename A::pint_t* pointer;
1266   typedef typename A::pint_t& reference;
1267   typedef size_t size_type;
1268   typedef size_t difference_type;
1269 
1270   static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1271     return _Self(addressSpace, sects, 0);
1272   }
1273   static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
1274     return _Self(addressSpace, sects,
1275                  sects.arm_section_length / sizeof(EHABIIndexEntry));
1276   }
1277 
1278   EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1279       : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1280 
1281   _Self& operator++() { ++_i; return *this; }
1282   _Self& operator+=(size_t a) { _i += a; return *this; }
1283   _Self& operator--() { assert(_i > 0); --_i; return *this; }
1284   _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1285 
1286   _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1287   _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1288 
1289   size_t operator-(const _Self& other) { return _i - other._i; }
1290 
1291   bool operator==(const _Self& other) const {
1292     assert(_addressSpace == other._addressSpace);
1293     assert(_sects == other._sects);
1294     return _i == other._i;
1295   }
1296 
1297   typename A::pint_t operator*() const { return functionAddress(); }
1298 
1299   typename A::pint_t functionAddress() const {
1300     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1301         EHABIIndexEntry, _i, functionOffset);
1302     return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1303   }
1304 
1305   typename A::pint_t dataAddress() {
1306     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1307         EHABIIndexEntry, _i, data);
1308     return indexAddr;
1309   }
1310 
1311  private:
1312   size_t _i;
1313   A* _addressSpace;
1314   const UnwindInfoSections* _sects;
1315 };
1316 
1317 template <typename A, typename R>
1318 bool UnwindCursor<A, R>::getInfoFromEHABISection(
1319     pint_t pc,
1320     const UnwindInfoSections &sects) {
1321   EHABISectionIterator<A> begin =
1322       EHABISectionIterator<A>::begin(_addressSpace, sects);
1323   EHABISectionIterator<A> end =
1324       EHABISectionIterator<A>::end(_addressSpace, sects);
1325   if (begin == end)
1326     return false;
1327 
1328   EHABISectionIterator<A> itNextPC = std::upper_bound(begin, end, pc);
1329   if (itNextPC == begin)
1330     return false;
1331   EHABISectionIterator<A> itThisPC = itNextPC - 1;
1332 
1333   pint_t thisPC = itThisPC.functionAddress();
1334   // If an exception is thrown from a function, corresponding to the last entry
1335   // in the table, we don't really know the function extent and have to choose a
1336   // value for nextPC. Choosing max() will allow the range check during trace to
1337   // succeed.
1338   pint_t nextPC = (itNextPC == end) ? std::numeric_limits<pint_t>::max()
1339                                     : itNextPC.functionAddress();
1340   pint_t indexDataAddr = itThisPC.dataAddress();
1341 
1342   if (indexDataAddr == 0)
1343     return false;
1344 
1345   uint32_t indexData = _addressSpace.get32(indexDataAddr);
1346   if (indexData == UNW_EXIDX_CANTUNWIND)
1347     return false;
1348 
1349   // If the high bit is set, the exception handling table entry is inline inside
1350   // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
1351   // the table points at an offset in the exception handling table (section 5 EHABI).
1352   pint_t exceptionTableAddr;
1353   uint32_t exceptionTableData;
1354   bool isSingleWordEHT;
1355   if (indexData & 0x80000000) {
1356     exceptionTableAddr = indexDataAddr;
1357     // TODO(ajwong): Should this data be 0?
1358     exceptionTableData = indexData;
1359     isSingleWordEHT = true;
1360   } else {
1361     exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1362     exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1363     isSingleWordEHT = false;
1364   }
1365 
1366   // Now we know the 3 things:
1367   //   exceptionTableAddr -- exception handler table entry.
1368   //   exceptionTableData -- the data inside the first word of the eht entry.
1369   //   isSingleWordEHT -- whether the entry is in the index.
1370   unw_word_t personalityRoutine = 0xbadf00d;
1371   bool scope32 = false;
1372   uintptr_t lsda;
1373 
1374   // If the high bit in the exception handling table entry is set, the entry is
1375   // in compact form (section 6.3 EHABI).
1376   if (exceptionTableData & 0x80000000) {
1377     // Grab the index of the personality routine from the compact form.
1378     uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1379     uint32_t extraWords = 0;
1380     switch (choice) {
1381       case 0:
1382         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1383         extraWords = 0;
1384         scope32 = false;
1385         lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
1386         break;
1387       case 1:
1388         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1389         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1390         scope32 = false;
1391         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1392         break;
1393       case 2:
1394         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1395         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1396         scope32 = true;
1397         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1398         break;
1399       default:
1400         _LIBUNWIND_ABORT("unknown personality routine");
1401         return false;
1402     }
1403 
1404     if (isSingleWordEHT) {
1405       if (extraWords != 0) {
1406         _LIBUNWIND_ABORT("index inlined table detected but pr function "
1407                          "requires extra words");
1408         return false;
1409       }
1410     }
1411   } else {
1412     pint_t personalityAddr =
1413         exceptionTableAddr + signExtendPrel31(exceptionTableData);
1414     personalityRoutine = personalityAddr;
1415 
1416     // ARM EHABI # 6.2, # 9.2
1417     //
1418     //  +---- ehtp
1419     //  v
1420     // +--------------------------------------+
1421     // | +--------+--------+--------+-------+ |
1422     // | |0| prel31 to personalityRoutine   | |
1423     // | +--------+--------+--------+-------+ |
1424     // | |      N |      unwind opcodes     | |  <-- UnwindData
1425     // | +--------+--------+--------+-------+ |
1426     // | | Word 2        unwind opcodes     | |
1427     // | +--------+--------+--------+-------+ |
1428     // | ...                                  |
1429     // | +--------+--------+--------+-------+ |
1430     // | | Word N        unwind opcodes     | |
1431     // | +--------+--------+--------+-------+ |
1432     // | | LSDA                             | |  <-- lsda
1433     // | | ...                              | |
1434     // | +--------+--------+--------+-------+ |
1435     // +--------------------------------------+
1436 
1437     uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1438     uint32_t FirstDataWord = *UnwindData;
1439     size_t N = ((FirstDataWord >> 24) & 0xff);
1440     size_t NDataWords = N + 1;
1441     lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1442   }
1443 
1444   _info.start_ip = thisPC;
1445   _info.end_ip = nextPC;
1446   _info.handler = personalityRoutine;
1447   _info.unwind_info = exceptionTableAddr;
1448   _info.lsda = lsda;
1449   // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
1450   _info.flags = isSingleWordEHT ? 1 : 0 | scope32 ? 0x2 : 0;  // Use enum?
1451 
1452   return true;
1453 }
1454 #endif
1455 
1456 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1457 template <typename A, typename R>
1458 bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1459                                                 const UnwindInfoSections &sects,
1460                                                 uint32_t fdeSectionOffsetHint) {
1461   typename CFI_Parser<A>::FDE_Info fdeInfo;
1462   typename CFI_Parser<A>::CIE_Info cieInfo;
1463   bool foundFDE = false;
1464   bool foundInCache = false;
1465   // If compact encoding table gave offset into dwarf section, go directly there
1466   if (fdeSectionOffsetHint != 0) {
1467     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1468                                     (uint32_t)sects.dwarf_section_length,
1469                                     sects.dwarf_section + fdeSectionOffsetHint,
1470                                     &fdeInfo, &cieInfo);
1471   }
1472 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1473   if (!foundFDE && (sects.dwarf_index_section != 0)) {
1474     foundFDE = EHHeaderParser<A>::findFDE(
1475         _addressSpace, pc, sects.dwarf_index_section,
1476         (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1477   }
1478 #endif
1479   if (!foundFDE) {
1480     // otherwise, search cache of previously found FDEs.
1481     pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1482     if (cachedFDE != 0) {
1483       foundFDE =
1484           CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1485                                  (uint32_t)sects.dwarf_section_length,
1486                                  cachedFDE, &fdeInfo, &cieInfo);
1487       foundInCache = foundFDE;
1488     }
1489   }
1490   if (!foundFDE) {
1491     // Still not found, do full scan of __eh_frame section.
1492     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1493                                       (uint32_t)sects.dwarf_section_length, 0,
1494                                       &fdeInfo, &cieInfo);
1495   }
1496   if (foundFDE) {
1497     typename CFI_Parser<A>::PrologInfo prolog;
1498     if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1499                                             &prolog)) {
1500       // Save off parsed FDE info
1501       _info.start_ip          = fdeInfo.pcStart;
1502       _info.end_ip            = fdeInfo.pcEnd;
1503       _info.lsda              = fdeInfo.lsda;
1504       _info.handler           = cieInfo.personality;
1505       _info.gp                = prolog.spExtraArgSize;
1506       _info.flags             = 0;
1507       _info.format            = dwarfEncoding();
1508       _info.unwind_info       = fdeInfo.fdeStart;
1509       _info.unwind_info_size  = (uint32_t)fdeInfo.fdeLength;
1510       _info.extra             = (unw_word_t) sects.dso_base;
1511 
1512       // Add to cache (to make next lookup faster) if we had no hint
1513       // and there was no index.
1514       if (!foundInCache && (fdeSectionOffsetHint == 0)) {
1515   #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1516         if (sects.dwarf_index_section == 0)
1517   #endif
1518         DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1519                               fdeInfo.fdeStart);
1520       }
1521       return true;
1522     }
1523   }
1524   //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
1525   return false;
1526 }
1527 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1528 
1529 
1530 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1531 template <typename A, typename R>
1532 bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1533                                               const UnwindInfoSections &sects) {
1534   const bool log = false;
1535   if (log)
1536     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1537             (uint64_t)pc, (uint64_t)sects.dso_base);
1538 
1539   const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1540                                                 sects.compact_unwind_section);
1541   if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1542     return false;
1543 
1544   // do a binary search of top level index to find page with unwind info
1545   pint_t targetFunctionOffset = pc - sects.dso_base;
1546   const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1547                                            sects.compact_unwind_section
1548                                          + sectionHeader.indexSectionOffset());
1549   uint32_t low = 0;
1550   uint32_t high = sectionHeader.indexCount();
1551   uint32_t last = high - 1;
1552   while (low < high) {
1553     uint32_t mid = (low + high) / 2;
1554     //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1555     //mid, low, high, topIndex.functionOffset(mid));
1556     if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1557       if ((mid == last) ||
1558           (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1559         low = mid;
1560         break;
1561       } else {
1562         low = mid + 1;
1563       }
1564     } else {
1565       high = mid;
1566     }
1567   }
1568   const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1569   const uint32_t firstLevelNextPageFunctionOffset =
1570       topIndex.functionOffset(low + 1);
1571   const pint_t secondLevelAddr =
1572       sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1573   const pint_t lsdaArrayStartAddr =
1574       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1575   const pint_t lsdaArrayEndAddr =
1576       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1577   if (log)
1578     fprintf(stderr, "\tfirst level search for result index=%d "
1579                     "to secondLevelAddr=0x%llX\n",
1580                     low, (uint64_t) secondLevelAddr);
1581   // do a binary search of second level page index
1582   uint32_t encoding = 0;
1583   pint_t funcStart = 0;
1584   pint_t funcEnd = 0;
1585   pint_t lsda = 0;
1586   pint_t personality = 0;
1587   uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1588   if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1589     // regular page
1590     UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1591                                                  secondLevelAddr);
1592     UnwindSectionRegularArray<A> pageIndex(
1593         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1594     // binary search looks for entry with e where index[e].offset <= pc <
1595     // index[e+1].offset
1596     if (log)
1597       fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1598                       "regular page starting at secondLevelAddr=0x%llX\n",
1599               (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1600     low = 0;
1601     high = pageHeader.entryCount();
1602     while (low < high) {
1603       uint32_t mid = (low + high) / 2;
1604       if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1605         if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1606           // at end of table
1607           low = mid;
1608           funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1609           break;
1610         } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1611           // next is too big, so we found it
1612           low = mid;
1613           funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1614           break;
1615         } else {
1616           low = mid + 1;
1617         }
1618       } else {
1619         high = mid;
1620       }
1621     }
1622     encoding = pageIndex.encoding(low);
1623     funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1624     if (pc < funcStart) {
1625       if (log)
1626         fprintf(
1627             stderr,
1628             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1629             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1630       return false;
1631     }
1632     if (pc > funcEnd) {
1633       if (log)
1634         fprintf(
1635             stderr,
1636             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1637             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1638       return false;
1639     }
1640   } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1641     // compressed page
1642     UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1643                                                     secondLevelAddr);
1644     UnwindSectionCompressedArray<A> pageIndex(
1645         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1646     const uint32_t targetFunctionPageOffset =
1647         (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1648     // binary search looks for entry with e where index[e].offset <= pc <
1649     // index[e+1].offset
1650     if (log)
1651       fprintf(stderr, "\tbinary search of compressed page starting at "
1652                       "secondLevelAddr=0x%llX\n",
1653               (uint64_t) secondLevelAddr);
1654     low = 0;
1655     last = pageHeader.entryCount() - 1;
1656     high = pageHeader.entryCount();
1657     while (low < high) {
1658       uint32_t mid = (low + high) / 2;
1659       if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1660         if ((mid == last) ||
1661             (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1662           low = mid;
1663           break;
1664         } else {
1665           low = mid + 1;
1666         }
1667       } else {
1668         high = mid;
1669       }
1670     }
1671     funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1672                                                               + sects.dso_base;
1673     if (low < last)
1674       funcEnd =
1675           pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1676                                                               + sects.dso_base;
1677     else
1678       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1679     if (pc < funcStart) {
1680       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1681                            "level compressed unwind table. funcStart=0x%llX",
1682                             (uint64_t) pc, (uint64_t) funcStart);
1683       return false;
1684     }
1685     if (pc > funcEnd) {
1686       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1687                           "level compressed unwind table. funcEnd=0x%llX",
1688                            (uint64_t) pc, (uint64_t) funcEnd);
1689       return false;
1690     }
1691     uint16_t encodingIndex = pageIndex.encodingIndex(low);
1692     if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1693       // encoding is in common table in section header
1694       encoding = _addressSpace.get32(
1695           sects.compact_unwind_section +
1696           sectionHeader.commonEncodingsArraySectionOffset() +
1697           encodingIndex * sizeof(uint32_t));
1698     } else {
1699       // encoding is in page specific table
1700       uint16_t pageEncodingIndex =
1701           encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1702       encoding = _addressSpace.get32(secondLevelAddr +
1703                                      pageHeader.encodingsPageOffset() +
1704                                      pageEncodingIndex * sizeof(uint32_t));
1705     }
1706   } else {
1707     _LIBUNWIND_DEBUG_LOG("malformed __unwind_info at 0x%0llX bad second "
1708                          "level page",
1709                           (uint64_t) sects.compact_unwind_section);
1710     return false;
1711   }
1712 
1713   // look up LSDA, if encoding says function has one
1714   if (encoding & UNWIND_HAS_LSDA) {
1715     UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1716     uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1717     low = 0;
1718     high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1719                     sizeof(unwind_info_section_header_lsda_index_entry);
1720     // binary search looks for entry with exact match for functionOffset
1721     if (log)
1722       fprintf(stderr,
1723               "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1724               funcStartOffset);
1725     while (low < high) {
1726       uint32_t mid = (low + high) / 2;
1727       if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1728         lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1729         break;
1730       } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1731         low = mid + 1;
1732       } else {
1733         high = mid;
1734       }
1735     }
1736     if (lsda == 0) {
1737       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
1738                     "pc=0x%0llX, but lsda table has no entry",
1739                     encoding, (uint64_t) pc);
1740       return false;
1741     }
1742   }
1743 
1744   // extact personality routine, if encoding says function has one
1745   uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1746                               (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1747   if (personalityIndex != 0) {
1748     --personalityIndex; // change 1-based to zero-based index
1749     if (personalityIndex > sectionHeader.personalityArrayCount()) {
1750       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d,  "
1751                             "but personality table has only %d entires",
1752                             encoding, personalityIndex,
1753                             sectionHeader.personalityArrayCount());
1754       return false;
1755     }
1756     int32_t personalityDelta = (int32_t)_addressSpace.get32(
1757         sects.compact_unwind_section +
1758         sectionHeader.personalityArraySectionOffset() +
1759         personalityIndex * sizeof(uint32_t));
1760     pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1761     personality = _addressSpace.getP(personalityPointer);
1762     if (log)
1763       fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1764                       "personalityDelta=0x%08X, personality=0x%08llX\n",
1765               (uint64_t) pc, personalityDelta, (uint64_t) personality);
1766   }
1767 
1768   if (log)
1769     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1770                     "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1771             (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1772   _info.start_ip = funcStart;
1773   _info.end_ip = funcEnd;
1774   _info.lsda = lsda;
1775   _info.handler = personality;
1776   _info.gp = 0;
1777   _info.flags = 0;
1778   _info.format = encoding;
1779   _info.unwind_info = 0;
1780   _info.unwind_info_size = 0;
1781   _info.extra = sects.dso_base;
1782   return true;
1783 }
1784 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1785 
1786 
1787 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1788 template <typename A, typename R>
1789 bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1790   pint_t base;
1791   RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1792   if (!unwindEntry) {
1793     _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1794     return false;
1795   }
1796   _info.gp = 0;
1797   _info.flags = 0;
1798   _info.format = 0;
1799   _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1800   _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1801   _info.extra = base;
1802   _info.start_ip = base + unwindEntry->BeginAddress;
1803 #ifdef _LIBUNWIND_TARGET_X86_64
1804   _info.end_ip = base + unwindEntry->EndAddress;
1805   // Only fill in the handler and LSDA if they're stale.
1806   if (pc != getLastPC()) {
1807     UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1808     if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1809       // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1810       // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1811       // these structures.)
1812       // N.B. UNWIND_INFO structs are DWORD-aligned.
1813       uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1814       const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1815       _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1816       if (*handler) {
1817         _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1818       } else
1819         _info.handler = 0;
1820     } else {
1821       _info.lsda = 0;
1822       _info.handler = 0;
1823     }
1824   }
1825 #elif defined(_LIBUNWIND_TARGET_ARM)
1826   _info.end_ip = _info.start_ip + unwindEntry->FunctionLength;
1827   _info.lsda = 0; // FIXME
1828   _info.handler = 0; // FIXME
1829 #endif
1830   setLastPC(pc);
1831   return true;
1832 }
1833 #endif
1834 
1835 
1836 template <typename A, typename R>
1837 void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
1838   pint_t pc = (pint_t)this->getReg(UNW_REG_IP);
1839 #if defined(_LIBUNWIND_ARM_EHABI)
1840   // Remove the thumb bit so the IP represents the actual instruction address.
1841   // This matches the behaviour of _Unwind_GetIP on arm.
1842   pc &= (pint_t)~0x1;
1843 #endif
1844 
1845   // If the last line of a function is a "throw" the compiler sometimes
1846   // emits no instructions after the call to __cxa_throw.  This means
1847   // the return address is actually the start of the next function.
1848   // To disambiguate this, back up the pc when we know it is a return
1849   // address.
1850   if (isReturnAddress)
1851     --pc;
1852 
1853   // Ask address space object to find unwind sections for this pc.
1854   UnwindInfoSections sects;
1855   if (_addressSpace.findUnwindSections(pc, sects)) {
1856 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1857     // If there is a compact unwind encoding table, look there first.
1858     if (sects.compact_unwind_section != 0) {
1859       if (this->getInfoFromCompactEncodingSection(pc, sects)) {
1860   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1861         // Found info in table, done unless encoding says to use dwarf.
1862         uint32_t dwarfOffset;
1863         if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
1864           if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
1865             // found info in dwarf, done
1866             return;
1867           }
1868         }
1869   #endif
1870         // If unwind table has entry, but entry says there is no unwind info,
1871         // record that we have no unwind info.
1872         if (_info.format == 0)
1873           _unwindInfoMissing = true;
1874         return;
1875       }
1876     }
1877 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1878 
1879 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1880     // If there is SEH unwind info, look there next.
1881     if (this->getInfoFromSEH(pc))
1882       return;
1883 #endif
1884 
1885 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1886     // If there is dwarf unwind info, look there next.
1887     if (sects.dwarf_section != 0) {
1888       if (this->getInfoFromDwarfSection(pc, sects)) {
1889         // found info in dwarf, done
1890         return;
1891       }
1892     }
1893 #endif
1894 
1895 #if defined(_LIBUNWIND_ARM_EHABI)
1896     // If there is ARM EHABI unwind info, look there next.
1897     if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
1898       return;
1899 #endif
1900   }
1901 
1902 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1903   // There is no static unwind info for this pc. Look to see if an FDE was
1904   // dynamically registered for it.
1905   pint_t cachedFDE = DwarfFDECache<A>::findFDE(0, pc);
1906   if (cachedFDE != 0) {
1907     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1908     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1909     const char *msg = CFI_Parser<A>::decodeFDE(_addressSpace,
1910                                                 cachedFDE, &fdeInfo, &cieInfo);
1911     if (msg == NULL) {
1912       typename CFI_Parser<A>::PrologInfo prolog;
1913       if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo,
1914                                                                 pc, &prolog)) {
1915         // save off parsed FDE info
1916         _info.start_ip         = fdeInfo.pcStart;
1917         _info.end_ip           = fdeInfo.pcEnd;
1918         _info.lsda             = fdeInfo.lsda;
1919         _info.handler          = cieInfo.personality;
1920         _info.gp               = prolog.spExtraArgSize;
1921                                   // Some frameless functions need SP
1922                                   // altered when resuming in function.
1923         _info.flags            = 0;
1924         _info.format           = dwarfEncoding();
1925         _info.unwind_info      = fdeInfo.fdeStart;
1926         _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1927         _info.extra            = 0;
1928         return;
1929       }
1930     }
1931   }
1932 
1933   // Lastly, ask AddressSpace object about platform specific ways to locate
1934   // other FDEs.
1935   pint_t fde;
1936   if (_addressSpace.findOtherFDE(pc, fde)) {
1937     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1938     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1939     if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
1940       // Double check this FDE is for a function that includes the pc.
1941       if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd)) {
1942         typename CFI_Parser<A>::PrologInfo prolog;
1943         if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo,
1944                                                 cieInfo, pc, &prolog)) {
1945           // save off parsed FDE info
1946           _info.start_ip         = fdeInfo.pcStart;
1947           _info.end_ip           = fdeInfo.pcEnd;
1948           _info.lsda             = fdeInfo.lsda;
1949           _info.handler          = cieInfo.personality;
1950           _info.gp               = prolog.spExtraArgSize;
1951           _info.flags            = 0;
1952           _info.format           = dwarfEncoding();
1953           _info.unwind_info      = fdeInfo.fdeStart;
1954           _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1955           _info.extra            = 0;
1956           return;
1957         }
1958       }
1959     }
1960   }
1961 #endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1962 
1963   // no unwind info, flag that we can't reliably unwind
1964   _unwindInfoMissing = true;
1965 }
1966 
1967 template <typename A, typename R>
1968 int UnwindCursor<A, R>::step() {
1969   // Bottom of stack is defined is when unwind info cannot be found.
1970   if (_unwindInfoMissing)
1971     return UNW_STEP_END;
1972 
1973   // Use unwinding info to modify register set as if function returned.
1974   int result;
1975 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1976   result = this->stepWithCompactEncoding();
1977 #elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1978   result = this->stepWithSEHData();
1979 #elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1980   result = this->stepWithDwarfFDE();
1981 #elif defined(_LIBUNWIND_ARM_EHABI)
1982   result = this->stepWithEHABI();
1983 #else
1984   #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
1985               _LIBUNWIND_SUPPORT_SEH_UNWIND or \
1986               _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
1987               _LIBUNWIND_ARM_EHABI
1988 #endif
1989 
1990   // update info based on new PC
1991   if (result == UNW_STEP_SUCCESS) {
1992     this->setInfoBasedOnIPRegister(true);
1993     if (_unwindInfoMissing)
1994       return UNW_STEP_END;
1995   }
1996 
1997   return result;
1998 }
1999 
2000 template <typename A, typename R>
2001 void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
2002   *info = _info;
2003 }
2004 
2005 template <typename A, typename R>
2006 bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2007                                                            unw_word_t *offset) {
2008   return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2009                                          buf, bufLen, offset);
2010 }
2011 
2012 } // namespace libunwind
2013 
2014 #endif // __UNWINDCURSOR_HPP__
2015